{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 通过 LangChain 和 Neo4j 引入 GraphRAG\n",
    "### 实现和评估 GraphRAG 应用程序"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 导入依赖"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_core.runnables import (\n",
    "    RunnableBranch,\n",
    "    RunnableLambda,\n",
    "    RunnableParallel,\n",
    "    RunnablePassthrough,\n",
    ")\n",
    "from langchain_core.prompts import ChatPromptTemplate\n",
    "from langchain_core.prompts.prompt import PromptTemplate\n",
    "from langchain_core.pydantic_v1 import BaseModel, Field\n",
    "from typing import Tuple, List, Optional\n",
    "from langchain_core.messages import AIMessage, HumanMessage\n",
    "from langchain_core.output_parsers import StrOutputParser\n",
    "import os\n",
    "from langchain_community.graphs import Neo4jGraph\n",
    "from langchain.document_loaders import WikipediaLoader\n",
    "from langchain.text_splitter import TokenTextSplitter\n",
    "from langchain_openai import ChatOpenAI\n",
    "from langchain_experimental.graph_transformers import LLMGraphTransformer\n",
    "from neo4j import GraphDatabase\n",
    "from yfiles_jupyter_graphs import GraphWidget\n",
    "from langchain_community.vectorstores import Neo4jVector\n",
    "from langchain_community.vectorstores.neo4j_vector import remove_lucene_chars\n",
    "from langchain_core.runnables import ConfigurableField, RunnableParallel, RunnablePassthrough\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 配置 LLM"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "from dotenv import load_dotenv\n",
    "from langchain_core.messages import HumanMessage\n",
    "from langchain_openai import AzureChatOpenAI\n",
    "\n",
    "\n",
    "load_dotenv()\n",
    "\n",
    "api_key = os.getenv(\"AZURE_OPENAI_API_KEY\")\n",
    "azure_endpoint = os.getenv(\"AZURE_OPENAI_ENDPOINT\")\n",
    "api_version = \"2023-07-01-preview\"\n",
    "\n",
    "llm = AzureChatOpenAI(\n",
    "    model=\"gpt-4\",\n",
    "    azure_deployment=\"gpt-4\",\n",
    "    api_key=api_key,\n",
    "    azure_endpoint=azure_endpoint,\n",
    "    openai_api_version=api_version,\n",
    ")\n",
    "\n",
    "from langchain_openai import AzureOpenAIEmbeddings\n",
    "\n",
    "embeddings = AzureOpenAIEmbeddings(\n",
    "    model=\"text-embedding-ada-002\",\n",
    "    api_key=api_key,\n",
    "    azure_endpoint=azure_endpoint,\n",
    "    openai_api_version=api_version,\n",
    ")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "AIMessage(content=\"J'aime la programmation.\", response_metadata={'token_usage': {'completion_tokens': 7, 'prompt_tokens': 19, 'total_tokens': 26}, 'model_name': 'gpt-4', 'system_fingerprint': 'fp_811936bd4f', 'prompt_filter_results': [{'prompt_index': 0, 'content_filter_results': {'hate': {'filtered': False, 'severity': 'safe'}, 'self_harm': {'filtered': False, 'severity': 'safe'}, 'sexual': {'filtered': False, 'severity': 'safe'}, 'violence': {'filtered': False, 'severity': 'safe'}}}], 'finish_reason': 'stop', 'logprobs': None, 'content_filter_results': {'hate': {'filtered': False, 'severity': 'safe'}, 'self_harm': {'filtered': False, 'severity': 'safe'}, 'sexual': {'filtered': False, 'severity': 'safe'}, 'violence': {'filtered': False, 'severity': 'safe'}}}, id='run-54892f59-bf15-40ae-91e9-e89378abd182-0')"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "message = HumanMessage(\n",
    "    content=\"Translate this sentence from English to French. I love programming.\"\n",
    ")\n",
    "llm.invoke([message])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 安装 neo4j 服务\n",
    "```shell\n",
    "docker run -d -p 7474:7474 -p 7687:7687 --name neo4j-apoc -e NEO4J_apoc_export_file_enabled=true -e NEO4J_apoc_import_file_enabled=true -e NEO4J_apoc_import_file_use__neo4j__config=true -e NEO4J_AUTH=neo4j/password -e NEO4J_PLUGINS=\\[\\\"apoc\\\"\\] neo4j:latest\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "#retrieving environmental variables from the .env file\n",
    "load_dotenv()\n",
    "\n",
    "#alternative\n",
    "os.environ[\"NEO4J_URI\"] = \"bolt://localhost:7687\"\n",
    "os.environ[\"NEO4J_USERNAME\"] = \"neo4j\"\n",
    "os.environ[\"NEO4J_PASSWORD\"] = \"password\"\n",
    "\n",
    "graph = Neo4jGraph()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 查询 AuraDB: Test Harry Potter"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Nodes:[Node(id='Mr. Dursley', type='Person'), Node(id='Mrs. Dursley', type='Person'), Node(id='Privet Drive', type='Location'), Node(id='Grunnings', type='Organization'), Node(id='Dudley', type='Person'), Node(id='Mrs. Potter', type='Person'), Node(id='Potters', type='Family')]\n",
      "Relationships:[Relationship(source=Node(id='Mr. Dursley', type='Person'), target=Node(id='Grunnings', type='Organization'), type='DIRECTOR'), Relationship(source=Node(id='Mr. Dursley', type='Person'), target=Node(id='Mrs. Dursley', type='Person'), type='SPOUSE'), Relationship(source=Node(id='Mr. Dursley', type='Person'), target=Node(id='Dudley', type='Person'), type='PARENT'), Relationship(source=Node(id='Mrs. Dursley', type='Person'), target=Node(id='Dudley', type='Person'), type='PARENT'), Relationship(source=Node(id='Mrs. Dursley', type='Person'), target=Node(id='Mrs. Potter', type='Person'), type='SISTER'), Relationship(source=Node(id='Mr. Dursley', type='Person'), target=Node(id='Privet Drive', type='Location'), type='RESIDENCE'), Relationship(source=Node(id='Mrs. Dursley', type='Person'), target=Node(id='Privet Drive', type='Location'), type='RESIDENCE')]\n"
     ]
    }
   ],
   "source": [
    "from langchain_core.documents import Document\n",
    "\n",
    "text = \"\"\"\n",
    "Mr. and Mrs. Dursley, of number four, Privet Drive, were proud to say\n",
    "that they were perfectly normal, thank you very much. They were the last\n",
    "people you'd expect to be involved in anything strange or mysterious,\n",
    "because they just didn't hold with such nonsense.\n",
    "Mr. Dursley was the director of a firm called Grunnings, which made\n",
    "drills. He was a big, beefy man with hardly any neck, although he did\n",
    "have a very large mustache. Mrs. Dursley was thin and blonde and had\n",
    "nearly twice the usual amount of neck, which came in very useful as she\n",
    "spent so much of her time craning over garden fences, spying on the\n",
    "neighbors. The Dursleys had a small son called Dudley and in their\n",
    "opinion there was no finer boy anywhere.\n",
    "The Dursleys had everything they wanted, but they also had a secret, and\n",
    "their greatest fear was that somebody would discover it. They didn't\n",
    "think they could bear it if anyone found out about the Potters. Mrs.\n",
    "Potter was Mrs. Dursley's sister, but they hadn't met for several years;\n",
    "in fact, Mrs. Dursley pretended she didn't have a sister, because her\n",
    "sister and her good-for-nothing husband were as unDursleyish as it was\n",
    "possible to be. The Dursleys shuddered to think what the neighbors would\n",
    "say if the Potters arrived in the street. The Dursleys knew that the\n",
    "Potters had a small son, too, but they had never even seen him. This boy\n",
    "was another good reason for keeping the Potters away; they didn't want\n",
    "Dudley mixing with a child like that.\n",
    "\"\"\"\n",
    "documents = [Document(page_content=text)]\n",
    "llm_transformer = LLMGraphTransformer(llm=llm)\n",
    "graph_documents = llm_transformer.convert_to_graph_documents(documents)\n",
    "print(f\"Nodes:{graph_documents[0].nodes}\")\n",
    "print(f\"Relationships:{graph_documents[0].relationships}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "graph.add_graph_documents(\n",
    "  graph_documents, \n",
    "  baseEntityLabel=True, \n",
    "  include_source=True\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "c2ed2408c3484cd3aaf5c2da5f6ff346",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "GraphWidget(layout=Layout(height='500px', width='100%'))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# directly show the graph resulting from the given Cypher query\n",
    "default_cypher = \"MATCH (s)-[r:!MENTIONS]->(t) RETURN s,r,t LIMIT 50\"\n",
    "\n",
    "def showGraph(cypher: str = default_cypher):\n",
    "    # create a neo4j session to run queries\n",
    "    driver = GraphDatabase.driver(\n",
    "        uri = os.environ[\"NEO4J_URI\"],\n",
    "        auth = (os.environ[\"NEO4J_USERNAME\"],\n",
    "                os.environ[\"NEO4J_PASSWORD\"]))\n",
    "    session = driver.session()\n",
    "    widget = GraphWidget(graph = session.run(cypher).graph())\n",
    "    widget.node_label_mapping = 'id'\n",
    "    #display(widget)\n",
    "    return widget\n",
    "\n",
    "showGraph()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 导入数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_openai import AzureOpenAIEmbeddings\n",
    "\n",
    "embeddings = AzureOpenAIEmbeddings(\n",
    "    model=\"text-embedding-ada-002\",\n",
    "    api_key=api_key,\n",
    "    azure_endpoint=azure_endpoint,\n",
    "    openai_api_version=api_version,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "vector_index = Neo4jVector.from_existing_graph(\n",
    "    embeddings,\n",
    "    search_type=\"hybrid\",\n",
    "    node_label=\"Document\",\n",
    "    text_node_properties=[\"text\"],\n",
    "    embedding_node_property=\"embedding\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "text: \n",
      "Mr. and Mrs. Dursley, of number four, Privet Drive, were proud to say\n",
      "that they were perfectly normal, thank you very much. They were the last\n",
      "people you'd expect to be involved in anything strange or mysterious,\n",
      "because they just didn't hold with such nonsense.\n",
      "Mr. Dursley was the director of a firm called Grunnings, which made\n",
      "drills. He was a big, beefy man with hardly any neck, although he did\n",
      "have a very large mustache. Mrs. Dursley was thin and blonde and had\n",
      "nearly twice the usual amount of neck, which came in very useful as she\n",
      "spent so much of her time craning over garden fences, spying on the\n",
      "neighbors. The Dursleys had a small son called Dudley and in their\n",
      "opinion there was no finer boy anywhere.\n",
      "The Dursleys had everything they wanted, but they also had a secret, and\n",
      "their greatest fear was that somebody would discover it. They didn't\n",
      "think they could bear it if anyone found out about the Potters. Mrs.\n",
      "Potter was Mrs. Dursley's sister, but they hadn't met for several years;\n",
      "in fact, Mrs. Dursley pretended she didn't have a sister, because her\n",
      "sister and her good-for-nothing husband were as unDursleyish as it was\n",
      "possible to be. The Dursleys shuddered to think what the neighbors would\n",
      "say if the Potters arrived in the street. The Dursleys knew that the\n",
      "Potters had a small son, too, but they had never even seen him. This boy\n",
      "was another good reason for keeping the Potters away; they didn't want\n",
      "Dudley mixing with a child like that.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "query = \"Who is Dudley?\"\n",
    "\n",
    "results = vector_index.similarity_search(query, k=1)\n",
    "print(results[0].page_content)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### CypherChain"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new GraphCypherQAChain chain...\u001b[0m\n",
      "Generated Cypher:\n",
      "\u001b[32;1m\u001b[1;3mMATCH (p:Person {id: \"Mr. Dursley\"})-[:WORKS_AT]->(o:Organization) RETURN o.id\u001b[0m\n",
      "Full Context:\n",
      "\u001b[32;1m\u001b[1;3m[{'o.id': 'Grunnings'}]\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'query': \"What is Mr. Dursley's job?\",\n",
       " 'result': 'Mr. Dursley works at Grunnings.'}"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from langchain.chains import GraphCypherQAChain\n",
    "\n",
    "chain = GraphCypherQAChain.from_llm(graph=graph, llm=llm, verbose=True)\n",
    "response = chain.invoke({\"query\": \"What is Mr. Dursley's job?\"})\n",
    "response"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### QAChain"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new RetrievalQA chain...\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'Mr. Dursley is the director of a firm called Grunnings, which makes drills.'"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from langchain.chains import RetrievalQA\n",
    "\n",
    "qa_chain = RetrievalQA.from_chain_type(\n",
    "    llm, retriever=vector_index.as_retriever(), verbose = True\n",
    ")\n",
    "\n",
    "result = qa_chain({\"query\": \"What is Mr. Dursley's job?\"})\n",
    "result[\"result\"]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## GraphRAG"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "raw_documents = WikipediaLoader(query=\"French Revolution\", load_max_docs = 10).load()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "from langchain_community.document_loaders import HuggingFaceDatasetLoader\n",
    "dataset_name = \"evidence_infer_treatment\"\n",
    "page_content_column = \"Text\"\n",
    "\n",
    "#loading only the first 100 rows of the dataset\n",
    "loader = HuggingFaceDatasetLoader(dataset_name, page_content_column, name = '2.0', )\n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "10"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "len(raw_documents)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[Document(page_content=\"The French Revolution was a period of political and societal change in France that began with the Estates General of 1789, and ended with the coup of 18 Brumaire in November 1799 and the formation of the French Consulate. Many of its ideas are considered fundamental principles of liberal democracy, while its values and institutions remain central to modern French political discourse.\\nIts causes are generally agreed to be a combination of social, political and economic factors, which the Ancien Régime proved unable to manage. A financial crisis and widespread social distress led in May 1789 to the convocation of the Estates General, which was converted into a National Assembly in June. The Storming of the Bastille on 14 July led to a series of radical measures by the Assembly, among them the abolition of feudalism, state control over the Catholic Church in France, and a declaration of rights.\\nThe next three years were dominated by the struggle for political control, exacerbated by economic depression. Military defeats following the outbreak of the French Revolutionary Wars in April 1792 resulted in the insurrection of 10 August 1792. The monarchy was abolished and replaced by the French First Republic in September, while Louis XVI was executed in January 1793.\\nAfter another revolt in June 1793, the constitution was suspended and effective political power passed from the National Convention to the Committee of Public Safety. About 16,000 people were executed in a Reign of Terror, which ended in July 1794. Weakened by external threats and internal opposition, the Republic was replaced in 1795 by the Directory. Four years later in 1799, the Consulate seized power in a military coup led by Napoleon Bonaparte. This is generally seen as marking the end of the Revolutionary period.\\n\\n\\n== Causes ==\\n\\nThe Revolution was the result of multiple long-term and short-term factors that culminated in a social, economic, financial and political crisis in the late 1780s. Combined with resistance to reform by the ruling elite, and indecisive policy by Louis XVI and his ministers, the state was unable to manage the crisis.\\nBetween 1715 and 1789, the French population grew from an estimated 21 to 28 million. The proportion of the population living in towns increased to 20%, and Paris alone had over 600,000 inhabitants. Peasants comprised about 80% of the population, but the middle classes tripled over the century, reaching almost 10% of the population by 1789. Although the 18th century was a period of increasing prosperity, the benefits were distributed unevenly across regions and social groups. Those whose income derived from agriculture, rents, interest and trade in goods from France's slave colonies benefited most, while the living standards of wage labourers and farmers on rented land fell. Increasing inequality led to more social conflict. Economic recession from 1785 and bad harvests in 1787 and 1788 led to high unemployment and food prices which coincided with a financial and political crisis for the monarchy.\\nWhile the state also experienced a debt crisis, the level of debt itself was not high compared with Britain's. A major problem was that tax rates varied widely from one region to another, were often different from the official amounts, and collected inconsistently. Its complexity meant uncertainty over the amount any authorised tax actually contributed, and caused resentment among all taxpayers. Attempts to simplify the system were blocked by the regional Parlements which approved financial policy. The resulting impasse led to the calling of the Estates-General, which became radicalised by the struggle for control of public finances.\\nLouis XVI was willing to consider reforms, but often backed down when faced with opposition from conservative elements within the nobility. Enlightenment critiques of social institutions were widely discussed among the educated French elite, while the American Revolution and the European revolts of the 1780s\", metadata={'title': 'French Revolution', 'summary': 'The French Revolution was a period of political and societal change in France that began with the Estates General of 1789, and ended with the coup of 18 Brumaire in November 1799 and the formation of the French Consulate. Many of its ideas are considered fundamental principles of liberal democracy, while its values and institutions remain central to modern French political discourse.\\nIts causes are generally agreed to be a combination of social, political and economic factors, which the Ancien Régime proved unable to manage. A financial crisis and widespread social distress led in May 1789 to the convocation of the Estates General, which was converted into a National Assembly in June. The Storming of the Bastille on 14 July led to a series of radical measures by the Assembly, among them the abolition of feudalism, state control over the Catholic Church in France, and a declaration of rights.\\nThe next three years were dominated by the struggle for political control, exacerbated by economic depression. Military defeats following the outbreak of the French Revolutionary Wars in April 1792 resulted in the insurrection of 10 August 1792. The monarchy was abolished and replaced by the French First Republic in September, while Louis XVI was executed in January 1793.\\nAfter another revolt in June 1793, the constitution was suspended and effective political power passed from the National Convention to the Committee of Public Safety. About 16,000 people were executed in a Reign of Terror, which ended in July 1794. Weakened by external threats and internal opposition, the Republic was replaced in 1795 by the Directory. Four years later in 1799, the Consulate seized power in a military coup led by Napoleon Bonaparte. This is generally seen as marking the end of the Revolutionary period.\\n\\n', 'source': 'https://en.wikipedia.org/wiki/French_Revolution'}),\n",
       " Document(page_content='The French Revolution of 1848 (French: Révolution française de 1848), also known as the February Revolution (Révolution de février), was a period of civil unrest in France, in February 1848, that led to the collapse of the July Monarchy and the foundation of the French Second Republic. It sparked the wave of revolutions of 1848.\\nThe revolution took place in Paris, and was preceded by the French government\\'s crackdown on the campagne des banquets. Starting on 22 February as a large-scale protest against the government of François Guizot, it later developed into a violent uprising against the monarchy. After intense urban fighting, large crowds managed to take control of the capital, leading to the abdication of King Louis Philippe on 24 February and the subsequent proclamation of the Second Republic.\\n\\n\\n== Background ==\\n\\nUnder the Charter of 1814, Louis XVIII ruled France as the head of a constitutional monarchy. Upon Louis XVIII\\'s death, his brother, the Count of Artois, ascended to the throne in 1824, as Charles X. Supported by the ultra-royalists, Charles X was an extremely unpopular reactionary monarch whose aspirations were far more grand than those of his deceased brother. He had no desire to rule as a constitutional monarch, taking various steps to strengthen his own authority as monarch and weaken that of the lower house.\\nIn 1830, Charles X of France, presumably instigated by one of his chief advisers, Jules, Prince de Polignac, issued the Four Ordinances of St. Cloud. These ordinances abolished freedom of the press, reduced the electorate by 75%, and dissolved the lower house. This action provoked an immediate reaction from the citizenry, who revolted against the monarchy during the Three Glorious Days of 26–29 July 1830. Charles was forced to abdicate the throne and to flee Paris for the United Kingdom. As a result, Louis Philippe, of the Orléanist branch, rose to power, replacing the old Charter by the Charter of 1830, and his rule became known as the July Monarchy.\\n\\nNicknamed the \"Bourgeois Monarch\", Louis Philippe sat at the head of a moderately liberal state controlled mainly by an educated elite.  He was supported by the Orléanists and opposed on his right by the Legitimists (former ultra-royalists) and on his left by the Republicans. Louis Philippe was an expert businessman and, by means of his businesses, he had become one of the richest men in France. Louis Philippe saw himself as the successful embodiment of a \"small businessman\" (petite bourgeoisie). He and his government did not look with favor on the big business (bourgeoisie), especially the industrial section of the French bourgeoisie, yet Louis Philippe did support the bankers, large and small. At the beginning of his reign in 1830, Jaques Laffitte, a banker and liberal politician who supported Louis Philippe\\'s rise to the throne, said \"From now on, the bankers will rule.\" \\nDuring the reign of Louis Philippe, the privileged \"financial aristocracy\", i.e. bankers, stock exchange magnates, railroad barons, owners of coal mines, iron ore mines, and forests and all landowners associated with them, tended to support him, while the industrial section of the bourgeoisie, which may have owned the land their factories sat on but not much more, were disfavored by Louis Philippe and actually tended to side with the middle class and laboring class in opposition to Louis Philippe in the Chamber of Deputies. Land-ownership was favored, and this elitism resulted in the disenfranchisement of much of the middle and working classes.\\nBy 1848, only about one percent of the population held the franchise. Although France had a free press and trial by jury, only landholders were permitted to vote, which alienated the petty bourgeoisie and even the industrial bourgeoisie from the government. Louis Philippe was viewed as generally indifferent to the needs of society, especially to those members of the middle class who were excluded from the political arena. Early in 1848, some Or', metadata={'title': 'French Revolution of 1848', 'summary': \"The French Revolution of 1848 (French: Révolution française de 1848), also known as the February Revolution (Révolution de février), was a period of civil unrest in France, in February 1848, that led to the collapse of the July Monarchy and the foundation of the French Second Republic. It sparked the wave of revolutions of 1848.\\nThe revolution took place in Paris, and was preceded by the French government's crackdown on the campagne des banquets. Starting on 22 February as a large-scale protest against the government of François Guizot, it later developed into a violent uprising against the monarchy. After intense urban fighting, large crowds managed to take control of the capital, leading to the abdication of King Louis Philippe on 24 February and the subsequent proclamation of the Second Republic.\", 'source': 'https://en.wikipedia.org/wiki/French_Revolution_of_1848'}),\n",
       " Document(page_content='The French Revolution of 1830, also known as the July Revolution (French: révolution de Juillet), Second French Revolution, or Trois Glorieuses (\"Three Glorious [Days]\"), was a second French Revolution after the first in 1789. It led to the overthrow of King Charles X, the French Bourbon monarch, and the ascent of his cousin Louis Philippe, Duke of Orléans. After 18 precarious years on the throne, Louis-Philippe was overthrown in the French Revolution of 1848. \\nThe 1830 Revolution marked a shift from one constitutional monarchy, under the restored House of Bourbon, to another, the July Monarchy; the transition of power from the House of Bourbon to its cadet branch, the House of Orléans; and the replacement of the principle of hereditary right by that of popular sovereignty. Supporters of the Bourbons would be called Legitimists, and supporters of Louis Philippe were known as Orléanists. In addition, there continued to be Bonapartists supporting the return of Napoleon\\'s descendants.\\n\\n\\n== Background ==\\nAfter Napoleonic France\\'s defeat and surrender in May 1814, Continental Europe, and France in particular, was in a state of disarray. The Congress of Vienna met to redraw the continent\\'s political map. Many European countries attended the Congress, but decision-making was controlled by four major powers: the Austrian Empire, represented by the Chief Minister Prince Metternich; the United Kingdom of Great Britain and Ireland, represented by its Foreign Secretary Viscount Castlereagh; the Russian Empire, represented by Emperor Alexander I; and Prussia, represented by King Frederick William III.\\nFrance\\'s foreign minister, Charles Maurice de Talleyrand, also attended the Congress. Although France was considered an enemy state, Talleyrand was allowed to attend the Congress because he claimed that he had only cooperated with Napoleon under duress. He suggested that France be restored to her \"legitimate\" (i.e. pre-Napoleonic) borders and governments—a plan that, with some changes, was accepted by the major powers. France was spared large annexations and returned to its 1791 borders. The House of Bourbon, deposed by the Revolution, was restored to the throne in the person of Louis XVIII. The Congress, however, forced Louis to grant a constitution, the Charter of 1814.\\n\\n\\n=== Charles X\\'s reign ===\\n\\nOn 16 September 1824, after a lingering illness of several months, the 68-year-old Louis XVIII died. As he was  childless, his younger brother, Charles, aged 66, inherited the throne of France. He was known to have more reactionary politics. On 27 September Charles X made his state entry into Paris to popular acclaim. During the ceremony, while presenting the King the keys to the city, the comte de Chabrol, Prefect of the Seine, declared: \"Proud to possess its new king, Paris can aspire to become the queen of cities by its magnificence, as its people aspire to be foremost in its fidelity, its devotion, and its love.\"\\nEight months later, the mood of the capital had sharply worsened in its opinion of the new king. The causes of this dramatic shift in public opinion were many, but the main two were:\\n\\nImposition of the death penalty for anyone profaning the Eucharist (see Anti-Sacrilege Act).\\nThe provisions for financial indemnities for properties confiscated by the 1789 Revolution and the First Empire of Napoleon—these indemnities to be paid to anyone, whether noble or non-noble, who had been declared \"enemies of the revolution.\"\\nCritics of the first accused the king and his new ministry of pandering to the Catholic Church, and by so doing of violating guarantees of equality of religious belief as specified in the Charter of 1814.\\nThe second matter, that of financial indemnities, was far more opportunistic than the first. Since the restoration of the monarchy, there had been demands from all groups to settle matters of property ownership in order to reduce, if not eliminate, the uncertainties in the real estate market. But opponents, many of whom we', metadata={'title': 'July Revolution', 'summary': 'The French Revolution of 1830, also known as the July Revolution (French: révolution de Juillet), Second French Revolution, or Trois Glorieuses (\"Three Glorious [Days]\"), was a second French Revolution after the first in 1789. It led to the overthrow of King Charles X, the French Bourbon monarch, and the ascent of his cousin Louis Philippe, Duke of Orléans. After 18 precarious years on the throne, Louis-Philippe was overthrown in the French Revolution of 1848. \\nThe 1830 Revolution marked a shift from one constitutional monarchy, under the restored House of Bourbon, to another, the July Monarchy; the transition of power from the House of Bourbon to its cadet branch, the House of Orléans; and the replacement of the principle of hereditary right by that of popular sovereignty. Supporters of the Bourbons would be called Legitimists, and supporters of Louis Philippe were known as Orléanists. In addition, there continued to be Bonapartists supporting the return of Napoleon\\'s descendants.', 'source': 'https://en.wikipedia.org/wiki/July_Revolution'}),\n",
       " Document(page_content='The following is a timeline of the French Revolution.\\n\\n\\n== 1788 – The royal treasury is empty; Prelude to the Revolution ==\\n\\n\\t\\t\\n\\t\\t\\t\\n\\t\\t\\t\\n\\t\\t\\n\\t\\t\\n\\t\\t\\t\\n\\t\\t\\t\\n\\t\\t\\n\\t\\t\\n\\t\\t\\t\\n\\t\\t\\t\\n\\t\\t\\n\\nJune 7: Day of the Tiles in Grenoble, first revolt against the king.\\nJuly 21: Assembly of Vizille, assembly of the Estates-General of Dauphiné.\\nAugust 8: The royal treasury is declared empty, and the Parlement of Paris refuses to reform the tax system or loan the Crown more money. To win their support for fiscal reforms, the Minister of Finance, Brienne, sets May 5, 1789, for a meeting of the Estates General, an assembly of the nobility, clergy, and commoners (the Third Estate), which has not met since 1614.\\nAugust 16: The treasury suspends payments on the debts of the government.\\nAugust 25: Brienne resigns as Minister of Finance, and is replaced by the Swiss banker Jacques Necker, who is popular with the Third Estate. French bankers and businessmen, who have always held Necker in high regard, agree to loan the state 75 million, on the condition that the Estates General will have full powers to reform the system. Necker was labelled an \"author of the revolution\" by Napoleon.\\nDecember 27:  Over the opposition of the nobles, Necker announces that the representation of the Third Estate will be doubled and that nobles and clergymen will be eligible to sit with the Third Estate.\\n\\n\\n== 1789 – The Revolution Begins; the Estates-General and the Constituent Assembly ==\\n\\n\\t\\t\\n\\t\\t\\t\\n\\t\\t\\t\\n\\t\\t\\n\\t\\t\\n\\t\\t\\t\\n\\t\\t\\t\\n\\t\\t\\n\\t\\t\\n\\t\\t\\t\\n\\t\\t\\t\\n\\t\\t\\n\\nJanuary 1789\\n\\nJanuary: The Abbé Emmanuel Joseph Sieyès publishes a pamphlet, What is the Third Estate?  he writes; \"What is the Third Estate? Everything. What has it been until now in the political order? Nothing. What does it demand to be? Something.\" The pamphlet is widely distributed.\\nJanuary 24: King Louis XVI convokes elections for delegates to the Estates-General\\nApril 1789\\n\\nApril 27: Riots in Paris by workers of the Réveillon wallpaper factory in the Faubourg Saint-Antoine. Twenty-five workers were killed in battles with police.\\nMay 1789\\n\\nMay 2: Presentation to the King of the Deputies of the Estates-General at Versailles. The clergy and nobles are welcomed with formal ceremonies and processions,  the Third Estate is not.\\nMay 5: Formal opening of the Estates-General at Versailles.\\nMay 6: The Deputies of the Third Estate refuses to meet separately from the other Estates, occupy the main hall, and invite the clergy and nobility to join them.\\nMay 11: The nobility refuses to meet together with the Third Estate, but the clergy hesitates, and suspends the verification of its deputies.\\nMay 20: The clergy renounces its special tax privileges, and accepts the principle of fiscal equality.\\nMay 22: The nobility renounces its special tax privileges.  However, the three estates are unable to agree on a common program.\\nMay 25: The Third Estate deputies from Paris, delayed by election procedures, arrive in Versailles.\\n\\nJune 1789\\n\\nJune 3: The scientist Jean Sylvain Bailly is chosen the leader of the Third Estate deputies.\\nJune 4: Upon the death of seven-year-old Louis Joseph Xavier François, Dauphin of France, the eldest son and heir of Louis XVI, his four-year-old brother, Louis-Charles, Duke of Normandy, becomes the new Dauphin.\\nJune 6: The deputies of the nobility reject a compromise program proposed by finance minister Jacques Necker.\\nJune 10: At the suggestion of Sieyès, the Third Estate deputies decide to hold their own meeting, and invite the other Estates to join them.\\nJune 13–14: Nine deputies from the clergy decide to join the meeting of the Third Estate.\\nJune 17: On the proposal of Sieyès, the deputies of the Third Estate declare themselves the National Assembly. To ensure popular support, they decree that taxes need only be paid while the Assembly is in session.\\nJune 19: By a vote of 149 to 137, the deputies of the clergy join the assembly of the Third Estate.\\nJune 20: On the orders of Louis XVI, the meeting hall of the Third Estate is closed and locked. At the', metadata={'title': 'Timeline of the French Revolution', 'summary': 'The following is a timeline of the French Revolution.', 'source': 'https://en.wikipedia.org/wiki/Timeline_of_the_French_Revolution'}),\n",
       " Document(page_content='The aim of a number of separate policies conducted by various governments of France during the French Revolution ranged from the appropriation by the government of the great landed estates and the large amounts of money held by the Catholic Church to the termination of Christian religious practice and of the religion itself. There has been much scholarly debate over whether the movement was popularly motivated or motivated by a small group of revolutionary radicals. These policies, which ended with the Concordat of 1801, formed the basis of the later and less radical laïcité policies.\\nThe French Revolution initially began with attacks on Church corruption and the wealth of the higher clergy, an action with which even many Christians could identify, since the Gallican Church held a dominant role in pre-revolutionary France. During a two-year period known as the Reign of Terror, the episodes of anti-clericalism became some the most violent of any in modern European history. The new revolutionary authorities suppressed the Church, abolished the Catholic monarchy, nationalized Church property, exiled 30,000 priests, and killed hundreds more.  In October 1793, the Christian calendar was replaced with one reckoned from the date of the Revolution, and Festivals of Liberty, Reason, and the Supreme Being were scheduled.  New forms of moral religion emerged, including the deistic Cult of the Supreme Being and the atheistic Cult of Reason, with the revolutionary government briefly mandating observance of the former in April 1794.\\n\\n\\n== Religion and the Catholic Church under the monarchy ==\\n\\n\\n=== Before 1789 ===\\nIn 18th-century France, the vast majority of the population adhered to the Catholic Church as Catholicism had been since the revocation of the Edict of Nantes in 1685 the only religion officially allowed in the kingdom. Nonetheless, minorities of French Protestants (mostly Huguenots & German Lutherans in Alsace) and Jews still lived in France at the beginning of the Revolution. The Edict of Versailles, commonly known as the Edict of Tolerance, had been signed by Louis XVI on 7 November 1787 did not give non-Catholics in France the right to openly practice their religions but only the rights to legal and civil status, which included the right to contract marriages without having to convert to the Catholic faith. At the same time, libertine thinkers popularized atheism and anti-clericalism.\\nThe Ancien Régime institutionalised the authority of the clergy in its status as the First Estate of the realm. As the largest landowner in the country, the Catholic Church controlled properties which provided massive revenues from its tenants; the Church also had an enormous income from the collection of tithes. Since the Church kept the registry of births, deaths, and marriages and was the only institution that provided hospitals and education in some parts of the country, it influenced all citizens.\\n\\n\\n=== Between 1789 and 1792 ===\\n\\nA milestone event of the Revolution was the abolition of the privileges of the First and Second Estate on the night of 4 August 1789. In particular, it abolished the tithes gathered by the Catholic clergy.\\nThe Declaration of the Rights of Man and Citizen of 1789 proclaimed freedom of religion across France in these terms:\\n\\nArticle IV – Liberty consists of doing anything which does not harm others: thus, the exercise of the natural rights of each man has only those borders which assure other members of the society the enjoyment of these same rights. These borders can be determined only by the law.\\nArticle X – No one may be disturbed for his opinions, even religious ones, provided that their manifestation does not trouble the public order established by the law.\\nOn 10 October 1789, the National Constituent Assembly seized the properties and land held by the Catholic Church and decided to sell them to fund the assignat Revolutionary currency.\\nOn 12 July 1790, the assembly passed the Civil Constitution of the Clergy that', metadata={'title': 'Dechristianization of France during the French Revolution', 'summary': 'The aim of a number of separate policies conducted by various governments of France during the French Revolution ranged from the appropriation by the government of the great landed estates and the large amounts of money held by the Catholic Church to the termination of Christian religious practice and of the religion itself. There has been much scholarly debate over whether the movement was popularly motivated or motivated by a small group of revolutionary radicals. These policies, which ended with the Concordat of 1801, formed the basis of the later and less radical laïcité policies.\\nThe French Revolution initially began with attacks on Church corruption and the wealth of the higher clergy, an action with which even many Christians could identify, since the Gallican Church held a dominant role in pre-revolutionary France. During a two-year period known as the Reign of Terror, the episodes of anti-clericalism became some the most violent of any in modern European history. The new revolutionary authorities suppressed the Church, abolished the Catholic monarchy, nationalized Church property, exiled 30,000 priests, and killed hundreds more.  In October 1793, the Christian calendar was replaced with one reckoned from the date of the Revolution, and Festivals of Liberty, Reason, and the Supreme Being were scheduled.  New forms of moral religion emerged, including the deistic Cult of the Supreme Being and the atheistic Cult of Reason, with the revolutionary government briefly mandating observance of the former in April 1794.\\n\\n', 'source': 'https://en.wikipedia.org/wiki/Dechristianization_of_France_during_the_French_Revolution'}),\n",
       " Document(page_content='Reflections on the Revolution in France is a political pamphlet written by the British statesman Edmund Burke and published in November 1790. It is fundamentally a contrast of the French Revolution to that time with the unwritten British Constitution and, to a significant degree, an argument with British supporters and interpreters of the events in France. One of the best-known intellectual attacks against the French Revolution, Reflections is a defining tract of modern conservatism as well as an important contribution to international theory. The Norton Anthology of English Literature describes Reflections as becoming the \"most eloquent statement of British conservatism favoring monarchy, aristocracy, property, hereditary succession, and the wisdom of the ages.\"  Above all else, it has been one of the defining efforts of Edmund Burke\\'s transformation of \"traditionalism into a self-conscious and fully conceived political philosophy of conservatism\".\\nThe pamphlet has not been easy to classify. Before seeing this work as a pamphlet, Burke wrote in the mode of a letter, invoking expectations of openness and selectivity that added a layer of meaning. Academics have had trouble identifying whether Burke, or his tract, can best be understood as \"a realist or an idealist, Rationalist or a Revolutionist\". Thanks to its thoroughness, rhetorical skill and literary power, it has become one of the most widely known of Burke\\'s writings and a classic text in political theory. In the 20th century, it influenced a number of conservative intellectuals, who recast Burke\\'s Whiggish arguments as a critique of Bolshevik programmes.\\n\\n\\n== Background ==\\n\\nBurke served in the House of Commons of Great Britain, representing the Whig party, in close alliance with liberal politician Lord Rockingham. In Burke\\'s political career, he vigorously defended constitutional limitation of the Crown\\'s authority, denounced the religious persecution of Catholics in his native Ireland, voiced the grievances of Britain\\'s American colonies, supported American Independence and vigorously pursued impeachment of Warren Hastings, the Governor-General of British India, for corruption and abuse of power. For these actions, Burke was widely respected by liberals in Great Britain, the United States and the European continent. Earlier in his career, Burke had championed many liberal causes and sided with the Americans in their war for independence. Thus, opponents and allies alike were surprised at the strength of his conviction that the French Revolution was \"a disaster\" and the revolutionists \"a swinish multitude\".\\nSoon after the fall of the Bastille in 1789, the French aristocrat Charles-Jean-François Depont asked his impressions of the Revolution and Burke replied with two letters. The longer, second letter, drafted after he read Richard Price\\'s speech A Discourse on the Love of Our Country in January 1790, became Reflections on the Revolution in France. Published in November 1790, the work was an instant bestseller as thirteen thousand copies were purchased in the first five weeks and by the following September had gone through eleven editions. According to Stephen Greenblatt in The Norton Anthology of English Literature, \"part of its appeal to contemporary readers lay in the highly wrought accounts of the mob\\'s violent treatment of the French king and queen (who at the time Burke was writing were imprisoned in Paris...).\"  The French king and queen were executed three years later, in January and October 1793 respectively.\\nBurke wrote that he did not like abstract thinking, that freedom and equality were different, that genuine equality must be judged by God and that liberty was a construct of the law and no excuse to do whatever one would like. He was not comfortable with radical change and believed that the revolutionaries would find themselves further in trouble as their actions would cause more problems. In his opinions, the revolutionaries did not understand that \"there', metadata={'title': 'Reflections on the Revolution in France', 'summary': 'Reflections on the Revolution in France is a political pamphlet written by the British statesman Edmund Burke and published in November 1790. It is fundamentally a contrast of the French Revolution to that time with the unwritten British Constitution and, to a significant degree, an argument with British supporters and interpreters of the events in France. One of the best-known intellectual attacks against the French Revolution, Reflections is a defining tract of modern conservatism as well as an important contribution to international theory. The Norton Anthology of English Literature describes Reflections as becoming the \"most eloquent statement of British conservatism favoring monarchy, aristocracy, property, hereditary succession, and the wisdom of the ages.\"  Above all else, it has been one of the defining efforts of Edmund Burke\\'s transformation of \"traditionalism into a self-conscious and fully conceived political philosophy of conservatism\".\\nThe pamphlet has not been easy to classify. Before seeing this work as a pamphlet, Burke wrote in the mode of a letter, invoking expectations of openness and selectivity that added a layer of meaning. Academics have had trouble identifying whether Burke, or his tract, can best be understood as \"a realist or an idealist, Rationalist or a Revolutionist\". Thanks to its thoroughness, rhetorical skill and literary power, it has become one of the most widely known of Burke\\'s writings and a classic text in political theory. In the 20th century, it influenced a number of conservative intellectuals, who recast Burke\\'s Whiggish arguments as a critique of Bolshevik programmes.\\n\\n', 'source': 'https://en.wikipedia.org/wiki/Reflections_on_the_Revolution_in_France'}),\n",
       " Document(page_content='The French Revolution had a major impact on Europe and the New World. Historians widely regard the Revolution as one of the most important events in European history. In the short-term, France lost thousands of its countrymen in the form of émigrés, or emigrants who wished to escape political tensions and save their lives.   A number of individuals settled in the neighboring countries (chiefly Great Britain, Germany and Austria), while some settled in Russia, and many also went to Canada and the United States.  The displacement of these Frenchmen led to a spread of French culture, policies regulating immigration, and a safe haven for Royalists and other counterrevolutionaries to outlast the violence of the French Revolution.  The long-term impact on France was profound, shaping politics, society, religion and ideas, and politics for more than a century.  The closer other countries were, the greater and deeper was the French impact, bringing liberalism, but also practices such as direct democracy and revolutionary terror along with the end of many feudal or traditional laws and practices.  However, there was also a conservative counter-reaction that defeated Napoleon, reinstalled the Bourbon kings, and in some ways reversed the new reforms.\\nMost of the new nations created by France were abolished and returned to prewar owners in 1814. However, Frederick Artz emphasizes the benefits the Italians gained from the French Revolution: \\n\\nFor nearly two decades the Italians had the excellent codes of law, a fair system of taxation, a better economic situation, and more religious and intellectual toleration than they had known for centuries.... Everywhere old physical, economic, and intellectual barriers had been thrown down and the Italians had begun to be aware of a common nationality.\\nLikewise in Switzerland the long-term impact of the French Revolution has been assessed by Martin: \\n\\nIt proclaimed the equality of citizens before the law, equality of languages, freedom of thought and faith; it created a Swiss citizenship, basis of our modern nationality, and the separation of powers, of which the old regime had no conception; it suppressed internal tariffs and other economic restraints; it unified weights and measures, reformed civil and penal law, authorized mixed marriages (between Catholics and Protestants), suppressed torture and improved justice; it developed education and public works.\\nThe greatest impact came in France itself. In addition to effects similar to those in Italy and Switzerland, France saw the introduction of the principle of legal equality, and the downgrading of the once powerful and rich Catholic Church to just a bureau controlled by the government. Power became centralized in Paris, with its strong bureaucracy and an army supplied by conscripting all young men. French politics were permanently polarized—\\'left\\' and \\'right\\'  were the new terms for the supporters and opponents of the principles of the Revolution.\\n\\n\\n== Impact on France ==\\n\\nThe changes in France were enormous; some were widely accepted and others were bitterly contested into the late 20th century.  Before the Revolution, the people had little power or voice. The kings had so thoroughly centralized the system that most nobles spent their time at Versailles, and played only a small direct role in their home districts. Thompson says that the kings had:\\n\"ruled by virtue of their personal wealth, their patronage of the nobility, their disposal of ecclesiastical offices, their provincial governors (intendants), their control over the judges and magistrates, and their command of the Army.\"\\nAfter the first year of revolution, this power had been stripped away. The king was a figurehead, the nobility had lost all their titles and most of their land, the Church lost its monasteries and farmlands, bishops, judges and magistrates were elected by the people, the army was almost helpless, with military power in the hands of the new revolutionary National Guard. T', metadata={'title': 'Influence of the French Revolution', 'summary': \"The French Revolution had a major impact on Europe and the New World. Historians widely regard the Revolution as one of the most important events in European history. In the short-term, France lost thousands of its countrymen in the form of émigrés, or emigrants who wished to escape political tensions and save their lives.   A number of individuals settled in the neighboring countries (chiefly Great Britain, Germany and Austria), while some settled in Russia, and many also went to Canada and the United States.  The displacement of these Frenchmen led to a spread of French culture, policies regulating immigration, and a safe haven for Royalists and other counterrevolutionaries to outlast the violence of the French Revolution.  The long-term impact on France was profound, shaping politics, society, religion and ideas, and politics for more than a century.  The closer other countries were, the greater and deeper was the French impact, bringing liberalism, but also practices such as direct democracy and revolutionary terror along with the end of many feudal or traditional laws and practices.  However, there was also a conservative counter-reaction that defeated Napoleon, reinstalled the Bourbon kings, and in some ways reversed the new reforms.\\nMost of the new nations created by France were abolished and returned to prewar owners in 1814. However, Frederick Artz emphasizes the benefits the Italians gained from the French Revolution: \\n\\nFor nearly two decades the Italians had the excellent codes of law, a fair system of taxation, a better economic situation, and more religious and intellectual toleration than they had known for centuries.... Everywhere old physical, economic, and intellectual barriers had been thrown down and the Italians had begun to be aware of a common nationality.\\nLikewise in Switzerland the long-term impact of the French Revolution has been assessed by Martin: \\n\\nIt proclaimed the equality of citizens before the law, equality of languages, freedom of thought and faith; it created a Swiss citizenship, basis of our modern nationality, and the separation of powers, of which the old regime had no conception; it suppressed internal tariffs and other economic restraints; it unified weights and measures, reformed civil and penal law, authorized mixed marriages (between Catholics and Protestants), suppressed torture and improved justice; it developed education and public works.\\nThe greatest impact came in France itself. In addition to effects similar to those in Italy and Switzerland, France saw the introduction of the principle of legal equality, and the downgrading of the once powerful and rich Catholic Church to just a bureau controlled by the government. Power became centralized in Paris, with its strong bureaucracy and an army supplied by conscripting all young men. French politics were permanently polarized—'left' and 'right'  were the new terms for the supporters and opponents of the principles of the Revolution.\\n\\n\", 'source': 'https://en.wikipedia.org/wiki/Influence_of_the_French_Revolution'}),\n",
       " Document(page_content='There is significant disagreement among historians of the French Revolution as to its causes. Usually, they acknowledge the presence of several interlinked factors, but vary in the weight they attribute to each one. These factors include cultural changes, normally associated with the Enlightenment; social change and financial and economic difficulties; and the political actions of the involved parties. For centuries, the French society was divided into three estates or orders. \\n\\nThe first estate, the highest class, consisted of clergy.\\nThe second estate consisted of the nobility.\\nThe third estate consisted of the commoners.  It included businessman, merchants, court officials, lawyers, peasants, landless labourers and servants.\\nThe first two estates together were 10% of the population.  The third estate was 90%.  All of the many types of taxes were paid by the third estate.  The society was based on the old French maxim \"The nobles fight; the clergy pray and the people pay\". \\nBeyond these relatively established facts about the social conditions surrounding the French Revolution, there is significant dissent among historians. Marxist historians, such as Lefebvre and Soboul, see the social tensions described here as the main cause of the revolution, as the Estates-General allowed them to manifest into tangible political action; the bourgeoisie and the lower classes were grouped into the third estate, allowing them to jointly oppose the establishment. Others see these social issues as important, but less so than the Enlightenment or the financial crisis; François Furet is a prominent proponent of the former, Simon Schama of the latter.\\n\\n\\n== Political background ==\\n\\nPrior to the revolution, France was a de jure absolute monarchy, a system that became known as the Ancien Régime. In practice, the power of the monarchy was typically checked by the nobility, the Roman Catholic Church, institutions such as the judicial parlements, national and local customs and, above all, the threat of insurrection. Prior to 1789, the last severe threat to the monarchy was the Fronde civil wars from 1648 to 1653, during the minority of Louis XIV. Although the earlier reign of Louis XIII had already seen a move towards centralization of the country, the adulthood of Louis XIV marked the peak of the French monarchy\\'s power. His tactics for bringing the nobility under control included inviting them to stay at his extravagant Palace of Versailles and participate in elaborate court rituals with a detailed code of etiquette.\\nSome scholars have argued that Louis XIV contributed to the monarchy\\'s downfall by failing to reform the government\\'s institutions while the monarchy was still secure. Others, including François Bluche, argue that Louis XIV cannot be held responsible for problems that would emerge over 70 years after his death.\\nHis successor Louis XV was less interested in governing and his reign saw a decline in the power of the monarchy. Historians generally describe his reign as a period of stagnation, foreign policy setbacks, and growing popular discontent against the monarchy. His affairs with a succession of mistresses also damaged its reputation.\\n\\nDuring the reign of Louis XVI, the power and prestige of the monarchy had declined to the point where the king struggled to overcome aristocratic resistance to fiscal reform, with the parlements often being focal points for this resistance. The parlements were regional courts of appeal that had the de facto power to block the implementation of legislation in their respective provinces. They were each dominated by the regional nobility. The power of the parlements had been curtailed by Louis XIV, but mostly reinstated during the minority of Louis XV. In 1770, Louis XV and René de Maupeou again curtailed the power of the parlements, except for the Parlement of Paris, the one that was the most powerful. Louis XVI reinstated them early in his reign. Alfred Cobban describes the Parlement of Paris as \"though ', metadata={'title': 'Causes of the French Revolution', 'summary': 'There is significant disagreement among historians of the French Revolution as to its causes. Usually, they acknowledge the presence of several interlinked factors, but vary in the weight they attribute to each one. These factors include cultural changes, normally associated with the Enlightenment; social change and financial and economic difficulties; and the political actions of the involved parties. For centuries, the French society was divided into three estates or orders. \\n\\nThe first estate, the highest class, consisted of clergy.\\nThe second estate consisted of the nobility.\\nThe third estate consisted of the commoners.  It included businessman, merchants, court officials, lawyers, peasants, landless labourers and servants.\\nThe first two estates together were 10% of the population.  The third estate was 90%.  All of the many types of taxes were paid by the third estate.  The society was based on the old French maxim \"The nobles fight; the clergy pray and the people pay\". \\nBeyond these relatively established facts about the social conditions surrounding the French Revolution, there is significant dissent among historians. Marxist historians, such as Lefebvre and Soboul, see the social tensions described here as the main cause of the revolution, as the Estates-General allowed them to manifest into tangible political action; the bourgeoisie and the lower classes were grouped into the third estate, allowing them to jointly oppose the establishment. Others see these social issues as important, but less so than the Enlightenment or the financial crisis; François Furet is a prominent proponent of the former, Simon Schama of the latter.\\n\\n', 'source': 'https://en.wikipedia.org/wiki/Causes_of_the_French_Revolution'}),\n",
       " Document(page_content='Historians since the late 20th century have debated how women shared in the French Revolution and what impact it had on French women. Women had no political rights in pre-Revolutionary France; they were considered \"passive\" citizens, forced to rely on men to determine what was best for them. That changed dramatically in theory as there seemingly were great advances in feminism. Feminism emerged in Paris as part of a broad demand for social and political reform. These women demanded equality for men and then moved on to a demand for the end of male domination. Their chief vehicle for agitation were pamphlets and women\\'s clubs, especially the Society of Revolutionary Republican Women. However, the Jacobin element in power abolished all the women\\'s clubs in October 1793 and arrested their leaders. The movement was crushed. Devance explains the decision in terms of the emphasis on masculinity in wartime, Marie Antoinette\\'s bad reputation for feminine interference in state affairs, and traditional male supremacy. A decade later the Napoleonic Code confirmed and perpetuated women\\'s second-class status.\\nThe French Revolution also had immense impact on the modern feminist movement as women\\'s rights resonates globally, inspiring movements like New Zealand\\'s suffrage bill and shaping the foundation of modern feminism, challenging traditional gender roles and advocating for universal equality. \\n\\n\\n== Traditional roles ==\\nWomen in pre-Revolutionary France could not vote or hold any political office. They were considered \"passive\" citizens, forced to rely on men to determine what was best for them in the government. It was the men who defined these categories, and women were forced to accept male domination in the political sphere.\\nSingle and married women had the same lack of rights. They did have rights in civil and criminal courts, which allowed their testimonies to be heard. In some instances, women were allowed to be part of contractual relationships however, they were not allowed to be part of notarized acts such as wills. For most women, all of their rights were under their father\\'s authority until marriage, then the authority would be passed down to the husband. Married women had no rights over themselves nor any property. Only in the instance of her husband\\'s death women would be allowed ownership over property. Laws and traditions confined women to work strenuous, labor-intensive jobs, which gave earnings that were significantly lower than men\\'s income, and did not allow rights to improve their status or become masters at their trade. Women had some political rights, including women in religious orders, noblewomen and some women of the Third Estate including widows. Their involvement in political matters pertained to being allowed to send representatives to participate in primary assemblies.\\nWomen were taught to be committed to their husbands and \"all his interests...[ Whatever it may be like cooking food, doing chores.]attention and care... [and] sincere and discreet zeal for his salvation.\" A woman\\'s education often consisted of learning to be a good wife and mother; thus, women were not supposed to be involved in the political sphere, as the limit of their influence was the raising of future citizens. The subservient role of women before the revolution was perhaps best exemplified by the Frederician Code, published in 1761 and attacked by Enlightenment philosophers and publications.\\nThe highly influential Encyclopédie in the 1750s set the tone of the Enlightenment, and its ideas exerted influence on the subsequent Revolution in France. Writing several articles on women in society, Louis de Jaucourt criticized traditional roles for women, arguing that \"it would be difficult to demonstrate that the husband\\'s rule comes from nature, in as much as this principle is contrary to natural human equality... a man does not invariably have more strength of body, of wisdom, of mind or conduct than a woman... The example of England and Russ', metadata={'title': 'Women in the French Revolution', 'summary': 'Historians since the late 20th century have debated how women shared in the French Revolution and what impact it had on French women. Women had no political rights in pre-Revolutionary France; they were considered \"passive\" citizens, forced to rely on men to determine what was best for them. That changed dramatically in theory as there seemingly were great advances in feminism. Feminism emerged in Paris as part of a broad demand for social and political reform. These women demanded equality for men and then moved on to a demand for the end of male domination. Their chief vehicle for agitation were pamphlets and women\\'s clubs, especially the Society of Revolutionary Republican Women. However, the Jacobin element in power abolished all the women\\'s clubs in October 1793 and arrested their leaders. The movement was crushed. Devance explains the decision in terms of the emphasis on masculinity in wartime, Marie Antoinette\\'s bad reputation for feminine interference in state affairs, and traditional male supremacy. A decade later the Napoleonic Code confirmed and perpetuated women\\'s second-class status.\\nThe French Revolution also had immense impact on the modern feminist movement as women\\'s rights resonates globally, inspiring movements like New Zealand\\'s suffrage bill and shaping the foundation of modern feminism, challenging traditional gender roles and advocating for universal equality.', 'source': 'https://en.wikipedia.org/wiki/Women_in_the_French_Revolution'}),\n",
       " Document(page_content='Romanticism originated in the second half of the 18th century at the same time as the French Revolution. Romanticism continued to grow in reaction to the effects of the social transformation caused by the Revolution. There are many signs of these effects of the French Revolution in various pieces of Romantic literature. By examining the influence of the French Revolution, one can determine that Romanticism arose as a reaction to the French Revolution. Instead of searching for rules governing nature and human beings, the romantics searched for a direct communication with nature and treated humans as unique individuals not subject to scientific rules.\\n\\n\\n== The influence of the French Revolution ==\\nThe French Revolution played a huge role in influencing Romantic writers. As the Revolution began to play out, the absolute monarchy that had ruled France for centuries collapsed in only three years.  This resulted in a complete transformation of society. A majority of the population was greatly in favor of this as the working class had been suffering oppression for many years. According to Albert Hancock, in his book The French Revolution and the English Poets: a study in historical criticism, \"The French Revolution came, bringing with it the promise of a brighter day, the promise of regenerated man and regenerated earth.  It was hailed with joy and acclamation by the oppressed, by the ardent lovers of humanity, by the poets, whose task it is to voice the human spirit.\"\\nA common theme among some of the most widely known romantic poets is their acceptance and approval of the French Revolution. William Wordsworth, Samuel Taylor Coleridge, Lord Byron, and Percy Shelley all shared the same view of the French Revolution as it being the beginning of a change in the current ways of society and helping to improve the lives of the oppressed. As the French Revolution changed the lives of virtually everyone in the nation and even continent because of its drastic and immediate shift in social reformation, it greatly influenced many writers at the time. Hancock writes, \"There is no need to recount here in detail how the French Revolution, at the close of the last century, was the great stimulus to the intellectual and emotional life of the civilized world, how it began by inspiring all liberty-loving men with hope and joy.\"\\nLiterature began to take a new turn when the spirit of the revolution caught the entire nation and turned things in a whole new direction. The newly acquired freedom of the common people did not only bring about just laws and living but ordinary people also had the freedom to think for themselves, and in turn the freedom to express themselves. Triggered by the revolutionary spirit, the writers of the time were full of creative ideas and were waiting for a chance to unleash them. Under the new laws writers and artists were given a considerable amount of freedom to express themselves which did well to pave the way to set a high standard for literature.\\nPrior to the French Revolution, poems and literature were typically written about and to aristocrats and clergy, and rarely for or about the working man. However, when the roles of society began to shift resulting from the French Revolution, and with the emergence of Romantic writers, this changed. Romantic poets such as Wordsworth, Coleridge, Byron, and Shelley started to write works for and about the working man; pieces that the common man could relate to.  According to Christensen, \"To get the real animating principle of the Romantic Movement, one must not study it inductively or abstractly; one must look at it historically.  It must be put beside the literary standards of the eighteenth century. These standards impose limits upon the Elysian fields of poetry; poetry must be confined to the common experience of average men… The Romantic Movement then means the revolt of a group of contemporary poets who wrote, not according to common and doctrinaire standards, but as they indivi', metadata={'title': 'Romanticism and the French Revolution', 'summary': 'Romanticism originated in the second half of the 18th century at the same time as the French Revolution. Romanticism continued to grow in reaction to the effects of the social transformation caused by the Revolution. There are many signs of these effects of the French Revolution in various pieces of Romantic literature. By examining the influence of the French Revolution, one can determine that Romanticism arose as a reaction to the French Revolution. Instead of searching for rules governing nature and human beings, the romantics searched for a direct communication with nature and treated humans as unique individuals not subject to scientific rules.', 'source': 'https://en.wikipedia.org/wiki/Romanticism_and_the_French_Revolution'})]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "raw_documents"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Document 0\n",
      "The French Revolution was a period of political and societal change in France that began with the Estates General of 1789, and ended with the coup of 18 Brumaire in November 1799 and the formation of the French Consulate. Many of its ideas are considered fundamental principles of liberal democracy, while its values and institutions remain central to modern French political discourse.\n",
      "Its causes are generally agreed to be a combination of social, political and economic factors, which the Ancien Régime proved unable to manage. A financial crisis and widespread social distress led in May 1789 to the convocation of the Estates General, which was converted into a National Assembly in June. The Storming of the Bastille on 14 July led to a series of radical measures by the Assembly, among them the abolition of feudalism, state control over the Catholic Church in France, and a declaration of rights.\n",
      "The next three years were dominated by the struggle for political control, exacerbated by economic depression. Military defeats following the outbreak of the French Revolutionary Wars in April 1792 resulted in the insurrection of 10 August 1792. The monarchy was abolished and replaced by the French First Republic in September, while Louis XVI was executed in January 1793.\n",
      "After another revolt in June 1793, the constitution was suspended and effective political power passed from the National Convention to the Committee of Public Safety. About 16,000 people were executed in a Reign of Terror, which ended in July 1794. Weakened by external threats and internal opposition, the Republic was replaced in 1795 by the Directory. Four years later in 1799, the Consulate seized power in a military coup led by Napoleon Bonaparte. This is generally seen as marking the end of the Revolutionary period.\n",
      "\n",
      "\n",
      "== Causes ==\n",
      "\n",
      "The Revolution was the result of multiple long-term and short-term factors that culminated in a social, economic, financial and political crisis in the late 1780s. Combined with resistance to reform by the ruling elite, and indecisive policy by Louis XVI and his ministers, the state was unable to manage the crisis.\n",
      "Between 1715 and 1789, the French population grew from an estimated 21 to 28 million. The proportion of the population living in towns increased to 20%, and Paris alone had over 600,000 inhabitants. Peasants comprised about 80% of the population, but the middle classes tripled over the century, reaching almost 10% of the population by 1789. Although the 18th century was a period of increasing prosperity, the benefits were distributed unevenly across regions and social groups. Those whose income derived from agriculture, rents, interest and trade in goods from France's slave colonies benefited most, while the living standards of wage labourers and farmers on rented land fell. Increasing inequality led to more social conflict. Economic recession from 1785 and bad harvests in 1787 and 1788 led to high unemployment and food prices which coincided with a financial and political crisis for the monarchy.\n",
      "While the state also experienced a debt crisis, the level of debt itself was not high compared with Britain's. A major problem was that tax rates varied widely from one region to another, were often different from the official amounts, and collected inconsistently. Its complexity meant uncertainty over the amount any authorised tax actually contributed, and caused resentment among all taxpayers. Attempts to simplify the system were blocked by the regional Parlements which approved financial policy. The resulting impasse led to the calling of the Estates-General, which became radicalised by the struggle for control of public finances.\n",
      "Louis XVI was willing to consider reforms, but often backed down when faced with opposition from conservative elements within the nobility. Enlightenment critiques of social institutions were widely discussed among the educated French elite, while the American Revolution and the European revolts of the 1780s\n",
      "Document 1\n",
      "The French Revolution of 1848 (French: Révolution française de 1848), also known as the February Revolution (Révolution de février), was a period of civil unrest in France, in February 1848, that led to the collapse of the July Monarchy and the foundation of the French Second Republic. It sparked the wave of revolutions of 1848.\n",
      "The revolution took place in Paris, and was preceded by the French government's crackdown on the campagne des banquets. Starting on 22 February as a large-scale protest against the government of François Guizot, it later developed into a violent uprising against the monarchy. After intense urban fighting, large crowds managed to take control of the capital, leading to the abdication of King Louis Philippe on 24 February and the subsequent proclamation of the Second Republic.\n",
      "\n",
      "\n",
      "== Background ==\n",
      "\n",
      "Under the Charter of 1814, Louis XVIII ruled France as the head of a constitutional monarchy. Upon Louis XVIII's death, his brother, the Count of Artois, ascended to the throne in 1824, as Charles X. Supported by the ultra-royalists, Charles X was an extremely unpopular reactionary monarch whose aspirations were far more grand than those of his deceased brother. He had no desire to rule as a constitutional monarch, taking various steps to strengthen his own authority as monarch and weaken that of the lower house.\n",
      "In 1830, Charles X of France, presumably instigated by one of his chief advisers, Jules, Prince de Polignac, issued the Four Ordinances of St. Cloud. These ordinances abolished freedom of the press, reduced the electorate by 75%, and dissolved the lower house. This action provoked an immediate reaction from the citizenry, who revolted against the monarchy during the Three Glorious Days of 26–29 July 1830. Charles was forced to abdicate the throne and to flee Paris for the United Kingdom. As a result, Louis Philippe, of the Orléanist branch, rose to power, replacing the old Charter by the Charter of 1830, and his rule became known as the July Monarchy.\n",
      "\n",
      "Nicknamed the \"Bourgeois Monarch\", Louis Philippe sat at the head of a moderately liberal state controlled mainly by an educated elite.  He was supported by the Orléanists and opposed on his right by the Legitimists (former ultra-royalists) and on his left by the Republicans. Louis Philippe was an expert businessman and, by means of his businesses, he had become one of the richest men in France. Louis Philippe saw himself as the successful embodiment of a \"small businessman\" (petite bourgeoisie). He and his government did not look with favor on the big business (bourgeoisie), especially the industrial section of the French bourgeoisie, yet Louis Philippe did support the bankers, large and small. At the beginning of his reign in 1830, Jaques Laffitte, a banker and liberal politician who supported Louis Philippe's rise to the throne, said \"From now on, the bankers will rule.\" \n",
      "During the reign of Louis Philippe, the privileged \"financial aristocracy\", i.e. bankers, stock exchange magnates, railroad barons, owners of coal mines, iron ore mines, and forests and all landowners associated with them, tended to support him, while the industrial section of the bourgeoisie, which may have owned the land their factories sat on but not much more, were disfavored by Louis Philippe and actually tended to side with the middle class and laboring class in opposition to Louis Philippe in the Chamber of Deputies. Land-ownership was favored, and this elitism resulted in the disenfranchisement of much of the middle and working classes.\n",
      "By 1848, only about one percent of the population held the franchise. Although France had a free press and trial by jury, only landholders were permitted to vote, which alienated the petty bourgeoisie and even the industrial bourgeoisie from the government. Louis Philippe was viewed as generally indifferent to the needs of society, especially to those members of the middle class who were excluded from the political arena. Early in 1848, some Or\n",
      "Document 2\n",
      "The French Revolution of 1830, also known as the July Revolution (French: révolution de Juillet), Second French Revolution, or Trois Glorieuses (\"Three Glorious [Days]\"), was a second French Revolution after the first in 1789. It led to the overthrow of King Charles X, the French Bourbon monarch, and the ascent of his cousin Louis Philippe, Duke of Orléans. After 18 precarious years on the throne, Louis-Philippe was overthrown in the French Revolution of 1848. \n",
      "The 1830 Revolution marked a shift from one constitutional monarchy, under the restored House of Bourbon, to another, the July Monarchy; the transition of power from the House of Bourbon to its cadet branch, the House of Orléans; and the replacement of the principle of hereditary right by that of popular sovereignty. Supporters of the Bourbons would be called Legitimists, and supporters of Louis Philippe were known as Orléanists. In addition, there continued to be Bonapartists supporting the return of Napoleon's descendants.\n",
      "\n",
      "\n",
      "== Background ==\n",
      "After Napoleonic France's defeat and surrender in May 1814, Continental Europe, and France in particular, was in a state of disarray. The Congress of Vienna met to redraw the continent's political map. Many European countries attended the Congress, but decision-making was controlled by four major powers: the Austrian Empire, represented by the Chief Minister Prince Metternich; the United Kingdom of Great Britain and Ireland, represented by its Foreign Secretary Viscount Castlereagh; the Russian Empire, represented by Emperor Alexander I; and Prussia, represented by King Frederick William III.\n",
      "France's foreign minister, Charles Maurice de Talleyrand, also attended the Congress. Although France was considered an enemy state, Talleyrand was allowed to attend the Congress because he claimed that he had only cooperated with Napoleon under duress. He suggested that France be restored to her \"legitimate\" (i.e. pre-Napoleonic) borders and governments—a plan that, with some changes, was accepted by the major powers. France was spared large annexations and returned to its 1791 borders. The House of Bourbon, deposed by the Revolution, was restored to the throne in the person of Louis XVIII. The Congress, however, forced Louis to grant a constitution, the Charter of 1814.\n",
      "\n",
      "\n",
      "=== Charles X's reign ===\n",
      "\n",
      "On 16 September 1824, after a lingering illness of several months, the 68-year-old Louis XVIII died. As he was  childless, his younger brother, Charles, aged 66, inherited the throne of France. He was known to have more reactionary politics. On 27 September Charles X made his state entry into Paris to popular acclaim. During the ceremony, while presenting the King the keys to the city, the comte de Chabrol, Prefect of the Seine, declared: \"Proud to possess its new king, Paris can aspire to become the queen of cities by its magnificence, as its people aspire to be foremost in its fidelity, its devotion, and its love.\"\n",
      "Eight months later, the mood of the capital had sharply worsened in its opinion of the new king. The causes of this dramatic shift in public opinion were many, but the main two were:\n",
      "\n",
      "Imposition of the death penalty for anyone profaning the Eucharist (see Anti-Sacrilege Act).\n",
      "The provisions for financial indemnities for properties confiscated by the 1789 Revolution and the First Empire of Napoleon—these indemnities to be paid to anyone, whether noble or non-noble, who had been declared \"enemies of the revolution.\"\n",
      "Critics of the first accused the king and his new ministry of pandering to the Catholic Church, and by so doing of violating guarantees of equality of religious belief as specified in the Charter of 1814.\n",
      "The second matter, that of financial indemnities, was far more opportunistic than the first. Since the restoration of the monarchy, there had been demands from all groups to settle matters of property ownership in order to reduce, if not eliminate, the uncertainties in the real estate market. But opponents, many of whom we\n",
      "Document 3\n",
      "The following is a timeline of the French Revolution.\n",
      "\n",
      "\n",
      "== 1788 – The royal treasury is empty; Prelude to the Revolution ==\n",
      "\n",
      "\t\t\n",
      "\t\t\t\n",
      "\t\t\t\n",
      "\t\t\n",
      "\t\t\n",
      "\t\t\t\n",
      "\t\t\t\n",
      "\t\t\n",
      "\t\t\n",
      "\t\t\t\n",
      "\t\t\t\n",
      "\t\t\n",
      "\n",
      "June 7: Day of the Tiles in Grenoble, first revolt against the king.\n",
      "July 21: Assembly of Vizille, assembly of the Estates-General of Dauphiné.\n",
      "August 8: The royal treasury is declared empty, and the Parlement of Paris refuses to reform the tax system or loan the Crown more money. To win their support for fiscal reforms, the Minister of Finance, Brienne, sets May 5, 1789, for a meeting of the Estates General, an assembly of the nobility, clergy, and commoners (the Third Estate), which has not met since 1614.\n",
      "August 16: The treasury suspends payments on the debts of the government.\n",
      "August 25: Brienne resigns as Minister of Finance, and is replaced by the Swiss banker Jacques Necker, who is popular with the Third Estate. French bankers and businessmen, who have always held Necker in high regard, agree to loan the state 75 million, on the condition that the Estates General will have full powers to reform the system. Necker was labelled an \"author of the revolution\" by Napoleon.\n",
      "December 27:  Over the opposition of the nobles, Necker announces that the representation of the Third Estate will be doubled and that nobles and clergymen will be eligible to sit with the Third Estate.\n",
      "\n",
      "\n",
      "== 1789 – The Revolution Begins; the Estates-General and the Constituent Assembly ==\n",
      "\n",
      "\t\t\n",
      "\t\t\t\n",
      "\t\t\t\n",
      "\t\t\n",
      "\t\t\n",
      "\t\t\t\n",
      "\t\t\t\n",
      "\t\t\n",
      "\t\t\n",
      "\t\t\t\n",
      "\t\t\t\n",
      "\t\t\n",
      "\n",
      "January 1789\n",
      "\n",
      "January: The Abbé Emmanuel Joseph Sieyès publishes a pamphlet, What is the Third Estate?  he writes; \"What is the Third Estate? Everything. What has it been until now in the political order? Nothing. What does it demand to be? Something.\" The pamphlet is widely distributed.\n",
      "January 24: King Louis XVI convokes elections for delegates to the Estates-General\n",
      "April 1789\n",
      "\n",
      "April 27: Riots in Paris by workers of the Réveillon wallpaper factory in the Faubourg Saint-Antoine. Twenty-five workers were killed in battles with police.\n",
      "May 1789\n",
      "\n",
      "May 2: Presentation to the King of the Deputies of the Estates-General at Versailles. The clergy and nobles are welcomed with formal ceremonies and processions,  the Third Estate is not.\n",
      "May 5: Formal opening of the Estates-General at Versailles.\n",
      "May 6: The Deputies of the Third Estate refuses to meet separately from the other Estates, occupy the main hall, and invite the clergy and nobility to join them.\n",
      "May 11: The nobility refuses to meet together with the Third Estate, but the clergy hesitates, and suspends the verification of its deputies.\n",
      "May 20: The clergy renounces its special tax privileges, and accepts the principle of fiscal equality.\n",
      "May 22: The nobility renounces its special tax privileges.  However, the three estates are unable to agree on a common program.\n",
      "May 25: The Third Estate deputies from Paris, delayed by election procedures, arrive in Versailles.\n",
      "\n",
      "June 1789\n",
      "\n",
      "June 3: The scientist Jean Sylvain Bailly is chosen the leader of the Third Estate deputies.\n",
      "June 4: Upon the death of seven-year-old Louis Joseph Xavier François, Dauphin of France, the eldest son and heir of Louis XVI, his four-year-old brother, Louis-Charles, Duke of Normandy, becomes the new Dauphin.\n",
      "June 6: The deputies of the nobility reject a compromise program proposed by finance minister Jacques Necker.\n",
      "June 10: At the suggestion of Sieyès, the Third Estate deputies decide to hold their own meeting, and invite the other Estates to join them.\n",
      "June 13–14: Nine deputies from the clergy decide to join the meeting of the Third Estate.\n",
      "June 17: On the proposal of Sieyès, the deputies of the Third Estate declare themselves the National Assembly. To ensure popular support, they decree that taxes need only be paid while the Assembly is in session.\n",
      "June 19: By a vote of 149 to 137, the deputies of the clergy join the assembly of the Third Estate.\n",
      "June 20: On the orders of Louis XVI, the meeting hall of the Third Estate is closed and locked. At the\n",
      "Document 4\n",
      "The aim of a number of separate policies conducted by various governments of France during the French Revolution ranged from the appropriation by the government of the great landed estates and the large amounts of money held by the Catholic Church to the termination of Christian religious practice and of the religion itself. There has been much scholarly debate over whether the movement was popularly motivated or motivated by a small group of revolutionary radicals. These policies, which ended with the Concordat of 1801, formed the basis of the later and less radical laïcité policies.\n",
      "The French Revolution initially began with attacks on Church corruption and the wealth of the higher clergy, an action with which even many Christians could identify, since the Gallican Church held a dominant role in pre-revolutionary France. During a two-year period known as the Reign of Terror, the episodes of anti-clericalism became some the most violent of any in modern European history. The new revolutionary authorities suppressed the Church, abolished the Catholic monarchy, nationalized Church property, exiled 30,000 priests, and killed hundreds more.  In October 1793, the Christian calendar was replaced with one reckoned from the date of the Revolution, and Festivals of Liberty, Reason, and the Supreme Being were scheduled.  New forms of moral religion emerged, including the deistic Cult of the Supreme Being and the atheistic Cult of Reason, with the revolutionary government briefly mandating observance of the former in April 1794.\n",
      "\n",
      "\n",
      "== Religion and the Catholic Church under the monarchy ==\n",
      "\n",
      "\n",
      "=== Before 1789 ===\n",
      "In 18th-century France, the vast majority of the population adhered to the Catholic Church as Catholicism had been since the revocation of the Edict of Nantes in 1685 the only religion officially allowed in the kingdom. Nonetheless, minorities of French Protestants (mostly Huguenots & German Lutherans in Alsace) and Jews still lived in France at the beginning of the Revolution. The Edict of Versailles, commonly known as the Edict of Tolerance, had been signed by Louis XVI on 7 November 1787 did not give non-Catholics in France the right to openly practice their religions but only the rights to legal and civil status, which included the right to contract marriages without having to convert to the Catholic faith. At the same time, libertine thinkers popularized atheism and anti-clericalism.\n",
      "The Ancien Régime institutionalised the authority of the clergy in its status as the First Estate of the realm. As the largest landowner in the country, the Catholic Church controlled properties which provided massive revenues from its tenants; the Church also had an enormous income from the collection of tithes. Since the Church kept the registry of births, deaths, and marriages and was the only institution that provided hospitals and education in some parts of the country, it influenced all citizens.\n",
      "\n",
      "\n",
      "=== Between 1789 and 1792 ===\n",
      "\n",
      "A milestone event of the Revolution was the abolition of the privileges of the First and Second Estate on the night of 4 August 1789. In particular, it abolished the tithes gathered by the Catholic clergy.\n",
      "The Declaration of the Rights of Man and Citizen of 1789 proclaimed freedom of religion across France in these terms:\n",
      "\n",
      "Article IV – Liberty consists of doing anything which does not harm others: thus, the exercise of the natural rights of each man has only those borders which assure other members of the society the enjoyment of these same rights. These borders can be determined only by the law.\n",
      "Article X – No one may be disturbed for his opinions, even religious ones, provided that their manifestation does not trouble the public order established by the law.\n",
      "On 10 October 1789, the National Constituent Assembly seized the properties and land held by the Catholic Church and decided to sell them to fund the assignat Revolutionary currency.\n",
      "On 12 July 1790, the assembly passed the Civil Constitution of the Clergy that\n",
      "Document 5\n",
      "Reflections on the Revolution in France is a political pamphlet written by the British statesman Edmund Burke and published in November 1790. It is fundamentally a contrast of the French Revolution to that time with the unwritten British Constitution and, to a significant degree, an argument with British supporters and interpreters of the events in France. One of the best-known intellectual attacks against the French Revolution, Reflections is a defining tract of modern conservatism as well as an important contribution to international theory. The Norton Anthology of English Literature describes Reflections as becoming the \"most eloquent statement of British conservatism favoring monarchy, aristocracy, property, hereditary succession, and the wisdom of the ages.\"  Above all else, it has been one of the defining efforts of Edmund Burke's transformation of \"traditionalism into a self-conscious and fully conceived political philosophy of conservatism\".\n",
      "The pamphlet has not been easy to classify. Before seeing this work as a pamphlet, Burke wrote in the mode of a letter, invoking expectations of openness and selectivity that added a layer of meaning. Academics have had trouble identifying whether Burke, or his tract, can best be understood as \"a realist or an idealist, Rationalist or a Revolutionist\". Thanks to its thoroughness, rhetorical skill and literary power, it has become one of the most widely known of Burke's writings and a classic text in political theory. In the 20th century, it influenced a number of conservative intellectuals, who recast Burke's Whiggish arguments as a critique of Bolshevik programmes.\n",
      "\n",
      "\n",
      "== Background ==\n",
      "\n",
      "Burke served in the House of Commons of Great Britain, representing the Whig party, in close alliance with liberal politician Lord Rockingham. In Burke's political career, he vigorously defended constitutional limitation of the Crown's authority, denounced the religious persecution of Catholics in his native Ireland, voiced the grievances of Britain's American colonies, supported American Independence and vigorously pursued impeachment of Warren Hastings, the Governor-General of British India, for corruption and abuse of power. For these actions, Burke was widely respected by liberals in Great Britain, the United States and the European continent. Earlier in his career, Burke had championed many liberal causes and sided with the Americans in their war for independence. Thus, opponents and allies alike were surprised at the strength of his conviction that the French Revolution was \"a disaster\" and the revolutionists \"a swinish multitude\".\n",
      "Soon after the fall of the Bastille in 1789, the French aristocrat Charles-Jean-François Depont asked his impressions of the Revolution and Burke replied with two letters. The longer, second letter, drafted after he read Richard Price's speech A Discourse on the Love of Our Country in January 1790, became Reflections on the Revolution in France. Published in November 1790, the work was an instant bestseller as thirteen thousand copies were purchased in the first five weeks and by the following September had gone through eleven editions. According to Stephen Greenblatt in The Norton Anthology of English Literature, \"part of its appeal to contemporary readers lay in the highly wrought accounts of the mob's violent treatment of the French king and queen (who at the time Burke was writing were imprisoned in Paris...).\"  The French king and queen were executed three years later, in January and October 1793 respectively.\n",
      "Burke wrote that he did not like abstract thinking, that freedom and equality were different, that genuine equality must be judged by God and that liberty was a construct of the law and no excuse to do whatever one would like. He was not comfortable with radical change and believed that the revolutionaries would find themselves further in trouble as their actions would cause more problems. In his opinions, the revolutionaries did not understand that \"there\n",
      "Document 6\n",
      "The French Revolution had a major impact on Europe and the New World. Historians widely regard the Revolution as one of the most important events in European history. In the short-term, France lost thousands of its countrymen in the form of émigrés, or emigrants who wished to escape political tensions and save their lives.   A number of individuals settled in the neighboring countries (chiefly Great Britain, Germany and Austria), while some settled in Russia, and many also went to Canada and the United States.  The displacement of these Frenchmen led to a spread of French culture, policies regulating immigration, and a safe haven for Royalists and other counterrevolutionaries to outlast the violence of the French Revolution.  The long-term impact on France was profound, shaping politics, society, religion and ideas, and politics for more than a century.  The closer other countries were, the greater and deeper was the French impact, bringing liberalism, but also practices such as direct democracy and revolutionary terror along with the end of many feudal or traditional laws and practices.  However, there was also a conservative counter-reaction that defeated Napoleon, reinstalled the Bourbon kings, and in some ways reversed the new reforms.\n",
      "Most of the new nations created by France were abolished and returned to prewar owners in 1814. However, Frederick Artz emphasizes the benefits the Italians gained from the French Revolution: \n",
      "\n",
      "For nearly two decades the Italians had the excellent codes of law, a fair system of taxation, a better economic situation, and more religious and intellectual toleration than they had known for centuries.... Everywhere old physical, economic, and intellectual barriers had been thrown down and the Italians had begun to be aware of a common nationality.\n",
      "Likewise in Switzerland the long-term impact of the French Revolution has been assessed by Martin: \n",
      "\n",
      "It proclaimed the equality of citizens before the law, equality of languages, freedom of thought and faith; it created a Swiss citizenship, basis of our modern nationality, and the separation of powers, of which the old regime had no conception; it suppressed internal tariffs and other economic restraints; it unified weights and measures, reformed civil and penal law, authorized mixed marriages (between Catholics and Protestants), suppressed torture and improved justice; it developed education and public works.\n",
      "The greatest impact came in France itself. In addition to effects similar to those in Italy and Switzerland, France saw the introduction of the principle of legal equality, and the downgrading of the once powerful and rich Catholic Church to just a bureau controlled by the government. Power became centralized in Paris, with its strong bureaucracy and an army supplied by conscripting all young men. French politics were permanently polarized—'left' and 'right'  were the new terms for the supporters and opponents of the principles of the Revolution.\n",
      "\n",
      "\n",
      "== Impact on France ==\n",
      "\n",
      "The changes in France were enormous; some were widely accepted and others were bitterly contested into the late 20th century.  Before the Revolution, the people had little power or voice. The kings had so thoroughly centralized the system that most nobles spent their time at Versailles, and played only a small direct role in their home districts. Thompson says that the kings had:\n",
      "\"ruled by virtue of their personal wealth, their patronage of the nobility, their disposal of ecclesiastical offices, their provincial governors (intendants), their control over the judges and magistrates, and their command of the Army.\"\n",
      "After the first year of revolution, this power had been stripped away. The king was a figurehead, the nobility had lost all their titles and most of their land, the Church lost its monasteries and farmlands, bishops, judges and magistrates were elected by the people, the army was almost helpless, with military power in the hands of the new revolutionary National Guard. T\n",
      "Document 7\n",
      "There is significant disagreement among historians of the French Revolution as to its causes. Usually, they acknowledge the presence of several interlinked factors, but vary in the weight they attribute to each one. These factors include cultural changes, normally associated with the Enlightenment; social change and financial and economic difficulties; and the political actions of the involved parties. For centuries, the French society was divided into three estates or orders. \n",
      "\n",
      "The first estate, the highest class, consisted of clergy.\n",
      "The second estate consisted of the nobility.\n",
      "The third estate consisted of the commoners.  It included businessman, merchants, court officials, lawyers, peasants, landless labourers and servants.\n",
      "The first two estates together were 10% of the population.  The third estate was 90%.  All of the many types of taxes were paid by the third estate.  The society was based on the old French maxim \"The nobles fight; the clergy pray and the people pay\". \n",
      "Beyond these relatively established facts about the social conditions surrounding the French Revolution, there is significant dissent among historians. Marxist historians, such as Lefebvre and Soboul, see the social tensions described here as the main cause of the revolution, as the Estates-General allowed them to manifest into tangible political action; the bourgeoisie and the lower classes were grouped into the third estate, allowing them to jointly oppose the establishment. Others see these social issues as important, but less so than the Enlightenment or the financial crisis; François Furet is a prominent proponent of the former, Simon Schama of the latter.\n",
      "\n",
      "\n",
      "== Political background ==\n",
      "\n",
      "Prior to the revolution, France was a de jure absolute monarchy, a system that became known as the Ancien Régime. In practice, the power of the monarchy was typically checked by the nobility, the Roman Catholic Church, institutions such as the judicial parlements, national and local customs and, above all, the threat of insurrection. Prior to 1789, the last severe threat to the monarchy was the Fronde civil wars from 1648 to 1653, during the minority of Louis XIV. Although the earlier reign of Louis XIII had already seen a move towards centralization of the country, the adulthood of Louis XIV marked the peak of the French monarchy's power. His tactics for bringing the nobility under control included inviting them to stay at his extravagant Palace of Versailles and participate in elaborate court rituals with a detailed code of etiquette.\n",
      "Some scholars have argued that Louis XIV contributed to the monarchy's downfall by failing to reform the government's institutions while the monarchy was still secure. Others, including François Bluche, argue that Louis XIV cannot be held responsible for problems that would emerge over 70 years after his death.\n",
      "His successor Louis XV was less interested in governing and his reign saw a decline in the power of the monarchy. Historians generally describe his reign as a period of stagnation, foreign policy setbacks, and growing popular discontent against the monarchy. His affairs with a succession of mistresses also damaged its reputation.\n",
      "\n",
      "During the reign of Louis XVI, the power and prestige of the monarchy had declined to the point where the king struggled to overcome aristocratic resistance to fiscal reform, with the parlements often being focal points for this resistance. The parlements were regional courts of appeal that had the de facto power to block the implementation of legislation in their respective provinces. They were each dominated by the regional nobility. The power of the parlements had been curtailed by Louis XIV, but mostly reinstated during the minority of Louis XV. In 1770, Louis XV and René de Maupeou again curtailed the power of the parlements, except for the Parlement of Paris, the one that was the most powerful. Louis XVI reinstated them early in his reign. Alfred Cobban describes the Parlement of Paris as \"though \n",
      "Document 8\n",
      "Historians since the late 20th century have debated how women shared in the French Revolution and what impact it had on French women. Women had no political rights in pre-Revolutionary France; they were considered \"passive\" citizens, forced to rely on men to determine what was best for them. That changed dramatically in theory as there seemingly were great advances in feminism. Feminism emerged in Paris as part of a broad demand for social and political reform. These women demanded equality for men and then moved on to a demand for the end of male domination. Their chief vehicle for agitation were pamphlets and women's clubs, especially the Society of Revolutionary Republican Women. However, the Jacobin element in power abolished all the women's clubs in October 1793 and arrested their leaders. The movement was crushed. Devance explains the decision in terms of the emphasis on masculinity in wartime, Marie Antoinette's bad reputation for feminine interference in state affairs, and traditional male supremacy. A decade later the Napoleonic Code confirmed and perpetuated women's second-class status.\n",
      "The French Revolution also had immense impact on the modern feminist movement as women's rights resonates globally, inspiring movements like New Zealand's suffrage bill and shaping the foundation of modern feminism, challenging traditional gender roles and advocating for universal equality. \n",
      "\n",
      "\n",
      "== Traditional roles ==\n",
      "Women in pre-Revolutionary France could not vote or hold any political office. They were considered \"passive\" citizens, forced to rely on men to determine what was best for them in the government. It was the men who defined these categories, and women were forced to accept male domination in the political sphere.\n",
      "Single and married women had the same lack of rights. They did have rights in civil and criminal courts, which allowed their testimonies to be heard. In some instances, women were allowed to be part of contractual relationships however, they were not allowed to be part of notarized acts such as wills. For most women, all of their rights were under their father's authority until marriage, then the authority would be passed down to the husband. Married women had no rights over themselves nor any property. Only in the instance of her husband's death women would be allowed ownership over property. Laws and traditions confined women to work strenuous, labor-intensive jobs, which gave earnings that were significantly lower than men's income, and did not allow rights to improve their status or become masters at their trade. Women had some political rights, including women in religious orders, noblewomen and some women of the Third Estate including widows. Their involvement in political matters pertained to being allowed to send representatives to participate in primary assemblies.\n",
      "Women were taught to be committed to their husbands and \"all his interests...[ Whatever it may be like cooking food, doing chores.]attention and care... [and] sincere and discreet zeal for his salvation.\" A woman's education often consisted of learning to be a good wife and mother; thus, women were not supposed to be involved in the political sphere, as the limit of their influence was the raising of future citizens. The subservient role of women before the revolution was perhaps best exemplified by the Frederician Code, published in 1761 and attacked by Enlightenment philosophers and publications.\n",
      "The highly influential Encyclopédie in the 1750s set the tone of the Enlightenment, and its ideas exerted influence on the subsequent Revolution in France. Writing several articles on women in society, Louis de Jaucourt criticized traditional roles for women, arguing that \"it would be difficult to demonstrate that the husband's rule comes from nature, in as much as this principle is contrary to natural human equality... a man does not invariably have more strength of body, of wisdom, of mind or conduct than a woman... The example of England and Russ\n",
      "Document 9\n",
      "Romanticism originated in the second half of the 18th century at the same time as the French Revolution. Romanticism continued to grow in reaction to the effects of the social transformation caused by the Revolution. There are many signs of these effects of the French Revolution in various pieces of Romantic literature. By examining the influence of the French Revolution, one can determine that Romanticism arose as a reaction to the French Revolution. Instead of searching for rules governing nature and human beings, the romantics searched for a direct communication with nature and treated humans as unique individuals not subject to scientific rules.\n",
      "\n",
      "\n",
      "== The influence of the French Revolution ==\n",
      "The French Revolution played a huge role in influencing Romantic writers. As the Revolution began to play out, the absolute monarchy that had ruled France for centuries collapsed in only three years.  This resulted in a complete transformation of society. A majority of the population was greatly in favor of this as the working class had been suffering oppression for many years. According to Albert Hancock, in his book The French Revolution and the English Poets: a study in historical criticism, \"The French Revolution came, bringing with it the promise of a brighter day, the promise of regenerated man and regenerated earth.  It was hailed with joy and acclamation by the oppressed, by the ardent lovers of humanity, by the poets, whose task it is to voice the human spirit.\"\n",
      "A common theme among some of the most widely known romantic poets is their acceptance and approval of the French Revolution. William Wordsworth, Samuel Taylor Coleridge, Lord Byron, and Percy Shelley all shared the same view of the French Revolution as it being the beginning of a change in the current ways of society and helping to improve the lives of the oppressed. As the French Revolution changed the lives of virtually everyone in the nation and even continent because of its drastic and immediate shift in social reformation, it greatly influenced many writers at the time. Hancock writes, \"There is no need to recount here in detail how the French Revolution, at the close of the last century, was the great stimulus to the intellectual and emotional life of the civilized world, how it began by inspiring all liberty-loving men with hope and joy.\"\n",
      "Literature began to take a new turn when the spirit of the revolution caught the entire nation and turned things in a whole new direction. The newly acquired freedom of the common people did not only bring about just laws and living but ordinary people also had the freedom to think for themselves, and in turn the freedom to express themselves. Triggered by the revolutionary spirit, the writers of the time were full of creative ideas and were waiting for a chance to unleash them. Under the new laws writers and artists were given a considerable amount of freedom to express themselves which did well to pave the way to set a high standard for literature.\n",
      "Prior to the French Revolution, poems and literature were typically written about and to aristocrats and clergy, and rarely for or about the working man. However, when the roles of society began to shift resulting from the French Revolution, and with the emergence of Romantic writers, this changed. Romantic poets such as Wordsworth, Coleridge, Byron, and Shelley started to write works for and about the working man; pieces that the common man could relate to.  According to Christensen, \"To get the real animating principle of the Romantic Movement, one must not study it inductively or abstractly; one must look at it historically.  It must be put beside the literary standards of the eighteenth century. These standards impose limits upon the Elysian fields of poetry; poetry must be confined to the common experience of average men… The Romantic Movement then means the revolt of a group of contemporary poets who wrote, not according to common and doctrinaire standards, but as they indivi\n"
     ]
    }
   ],
   "source": [
    "for i in range(len(raw_documents)):\n",
    "    print(f'Document {i}')\n",
    "    print(raw_documents[i].page_content)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{}"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from langchain_core.documents import Document\n",
    "#attributing an empty dict to the metadata field of each document\n",
    "raw_documents = [Document(page_content=doc.page_content, metadata={}) for doc in raw_documents]\n",
    "raw_documents[0].metadata"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define chunking strategy\n",
    "\n",
    "text_splitter = TokenTextSplitter(chunk_size=512, chunk_overlap=24)\n",
    "documents = text_splitter.split_documents(raw_documents)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pickle\n",
    "\n",
    "# Save the documents variable\n",
    "with open('documents.pkl', 'wb') as f:\n",
    "    pickle.dump(documents, f)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Storing documents in a GraphDB"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "llm_transformer = LLMGraphTransformer(llm=llm)\n",
    "\n",
    "graph_documents = llm_transformer.convert_to_graph_documents(documents)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "graph.add_graph_documents(\n",
    "    graph_documents,\n",
    "    baseEntityLabel=True,\n",
    "    include_source=True\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "b38d9342af144f2a9e31e31a9aa57b4e",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "GraphWidget(layout=Layout(height='800px', width='100%'))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# directly show the graph resulting from the given Cypher query\n",
    "default_cypher = \"MATCH (s)-[r:!MENTIONS]->(t) RETURN s,r,t LIMIT 50\"\n",
    "\n",
    "def showGraph(cypher: str = default_cypher):\n",
    "    # create a neo4j session to run queries\n",
    "    driver = GraphDatabase.driver(\n",
    "        uri = os.environ[\"NEO4J_URI\"],\n",
    "        auth = (os.environ[\"NEO4J_USERNAME\"],\n",
    "                os.environ[\"NEO4J_PASSWORD\"]))\n",
    "    session = driver.session()\n",
    "    widget = GraphWidget(graph = session.run(cypher).graph())\n",
    "    widget.node_label_mapping = 'id'\n",
    "    #display(widget)\n",
    "    return widget\n",
    "\n",
    "showGraph()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "vector_index = Neo4jVector.from_existing_graph(\n",
    "    embeddings,\n",
    "    search_type=\"hybrid\",\n",
    "    node_label=\"Document\",\n",
    "    text_node_properties=[\"text\"],\n",
    "    embedding_node_property=\"embedding\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new RetrievalQA chain...\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'The convocation of the Estates General in May 1789 was an attempt to address the financial crisis and other issues plaguing France. However, it did not immediately resolve these problems. The Estates General was a legislative assembly of the different classes (or estates) of French subjects. It had not been convened for 175 years prior to 1789, indicating the severity of the crisis at hand.\\n\\nThe calling of the Estates General was intended to be a way for the monarchy to discuss and approve new tax laws to resolve the financial crisis. It provided a platform for the three estates - the clergy, the nobility, and the commoners - to voice their grievances and propose solutions.\\n\\nHowever, the Estates General was not equipped to handle the depth of the crisis due to its structure and the conflicts between the estates. The Third Estate, representing the commoners who were the majority of the population and bore the brunt of the tax burden, was outvoted by the other two estates. This led to increasing tensions and disputes over representation, which eventually resulted in the Third Estate breaking away and declaring themselves the National Assembly.\\n\\nThis was a radical action that marked the beginning of the French Revolution. The National Assembly was determined to push for reforms, leading to significant changes such as the abolition of feudalism, state control over the Catholic Church in France, and a declaration of rights. So, while the convocation of the Estates General did not directly solve the crisis, it set in motion a series of events that led to radical political and societal change.'"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from langchain.chains import RetrievalQA\n",
    "\n",
    "qa_graph_chain = RetrievalQA.from_chain_type(\n",
    "    llm, retriever=vector_index.as_retriever(), verbose = True\n",
    ")\n",
    "\n",
    "result = qa_graph_chain({\"query\": \"Considering the financial crisis and resistance to reform by the Ancien Régime, how did the convocation of the Estates General in May 1789 specifically address these multifaceted issues?\"})\n",
    "result[\"result\"]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Graph only"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Defining each question as a variable\n",
    "question1 = \"How did the economic policies of the Ancien Régime contribute to the financial crisis that precipitated the French Revolution?\"\n",
    "question2 = \"In what ways did the social and political structure of the Estates-General contribute to its transformation into the National Assembly?\"\n",
    "question3 = \"What role did economic depression and military defeats play in the radicalization of the French Revolution in 1792?\"\n",
    "question4 = \"How did the French Revolutionary Wars affect the internal political landscape of France from 1792 to 1799?\"\n",
    "question5 = \"Examine the socio-economic reasons behind the calling of the Estates-General in 1789.\"\n",
    "question6 = \"How did Enlightenment ideas influence the legislative reforms of the National Assembly?\"\n",
    "question7 = \"What event directly led to the transformation of the Estates-General into the National Assembly in June 1789?\"\n",
    "question8 = \"Which radical measure taken by the National Assembly on July 14, 1789, symbolically marked the beginning of the French Revolution?\"\n",
    "question9 = \"Which governing body replaced the National Convention after the fall of Robespierre in 1794?\"\n",
    "question10 = \"What significant political change occurred in France on 18 Brumaire in 1799?\"\n",
    "question11 = \"Considering the financial difficulties faced by the Ancien Régime, how did the complex and inconsistent tax system contribute to the financial instability and eventual calling of the Estates-General?\"\n",
    "question12 = \"What role did the socio-economic pressures such as the increase in the population and the widening gap between the rich and the poor play in setting the stage for the French Revolution?\"\n",
    "question13 = \"How did the financial crisis, exacerbated by poor harvests and high food prices, lead to the convening of the Estates-General in 1789?\"\n",
    "question14 = \"Discuss the immediate political repercussions of the Storming of the Bastille on the French Revolution.\"\n",
    "\n",
    "# Creating a list of all questions\n",
    "questions = [question1, question2, question3, question4, question5, question6, question7, question8, question9, question10, question11, question12, question13, question14]\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "graph_results = []\n",
    "graph_source_documents = []\n",
    "for q in questions:\n",
    "    graph_results.append(graph_chain({\"query\": q})[\"result\"])\n",
    "    graph_source_documents.append(graph_chain({\"query\": q})[\"source_documents\"])\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>questions</th>\n",
       "      <th>graph_results</th>\n",
       "      <th>graph_source_documents</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>How did the economic policies of the Ancien Ré...</td>\n",
       "      <td>The economic policies of the Ancien Régime con...</td>\n",
       "      <td>[page_content=\"\\ntext: % of the population by ...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>In what ways did the social and political stru...</td>\n",
       "      <td>The social and political structure of the Esta...</td>\n",
       "      <td>[page_content='\\ntext: The French Revolution w...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>How did the Storming of the Bastille influence...</td>\n",
       "      <td>The text does not provide specific information...</td>\n",
       "      <td>[page_content='\\ntext:  introduction of the pr...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>What role did economic depression and military...</td>\n",
       "      <td>Economic depression and military defeats playe...</td>\n",
       "      <td>[page_content=\"\\ntext: % of the population by ...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>Discuss the impact of the Reign of Terror on t...</td>\n",
       "      <td>The text does not provide specific information...</td>\n",
       "      <td>[page_content='\\ntext:  introduction of the pr...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>What were the primary factors leading to the f...</td>\n",
       "      <td>The text does not provide specific information...</td>\n",
       "      <td>[page_content='\\ntext: The French Revolution w...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>How did the French Revolutionary Wars affect t...</td>\n",
       "      <td>The French Revolutionary Wars that began in 17...</td>\n",
       "      <td>[page_content='\\ntext: The French Revolution w...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>Examine the socio-economic reasons behind the ...</td>\n",
       "      <td>The calling of the Estates-General in 1789 was...</td>\n",
       "      <td>[page_content=\"\\ntext: % of the population by ...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>How did Enlightenment ideas influence the legi...</td>\n",
       "      <td>The Enlightenment ideas played a crucial role ...</td>\n",
       "      <td>[page_content='\\ntext:  introduction of the pr...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>Assess the role of Louis XVI’s indecisiveness ...</td>\n",
       "      <td>The text does not provide specific information...</td>\n",
       "      <td>[page_content='\\ntext:  rituals with a detaile...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>What event directly led to the transformation ...</td>\n",
       "      <td>On June 17, 1789, the deputies of the Third Es...</td>\n",
       "      <td>[page_content='\\ntext:  for delegates to the E...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>11</th>\n",
       "      <td>Which radical measure taken by the National As...</td>\n",
       "      <td>The Storming of the Bastille on July 14, 1789,...</td>\n",
       "      <td>[page_content='\\ntext: The French Revolution w...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>12</th>\n",
       "      <td>What was the immediate consequence of Louis XV...</td>\n",
       "      <td>The text does not provide information on the i...</td>\n",
       "      <td>[page_content='\\ntext:  rituals with a detaile...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>13</th>\n",
       "      <td>Which governing body replaced the National Con...</td>\n",
       "      <td>The governing body that replaced the National ...</td>\n",
       "      <td>[page_content='\\ntext: The French Revolution o...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>14</th>\n",
       "      <td>What significant political change occurred in ...</td>\n",
       "      <td>The significant political change that occurred...</td>\n",
       "      <td>[page_content='\\ntext: The French Revolution o...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>15</th>\n",
       "      <td>Considering the financial difficulties faced b...</td>\n",
       "      <td>The inconsistent and complex tax system in Fra...</td>\n",
       "      <td>[page_content=\"\\ntext: % of the population by ...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>16</th>\n",
       "      <td>What role did the socio-economic pressures suc...</td>\n",
       "      <td>The socio-economic pressures played a signific...</td>\n",
       "      <td>[page_content='\\ntext: There is significant di...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>17</th>\n",
       "      <td>Examine the influence of the Enlightenment on ...</td>\n",
       "      <td>The text does not provide specific information...</td>\n",
       "      <td>[page_content='\\ntext:  institutionalised the ...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>18</th>\n",
       "      <td>How did the financial crisis, exacerbated by p...</td>\n",
       "      <td>The financial crisis in France was primarily c...</td>\n",
       "      <td>[page_content=\"\\ntext: % of the population by ...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>19</th>\n",
       "      <td>Discuss the immediate political repercussions ...</td>\n",
       "      <td>The Storming of the Bastille in July 1789 mark...</td>\n",
       "      <td>[page_content='\\ntext:  introduction of the pr...</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                                            questions  \\\n",
       "0   How did the economic policies of the Ancien Ré...   \n",
       "1   In what ways did the social and political stru...   \n",
       "2   How did the Storming of the Bastille influence...   \n",
       "3   What role did economic depression and military...   \n",
       "4   Discuss the impact of the Reign of Terror on t...   \n",
       "5   What were the primary factors leading to the f...   \n",
       "6   How did the French Revolutionary Wars affect t...   \n",
       "7   Examine the socio-economic reasons behind the ...   \n",
       "8   How did Enlightenment ideas influence the legi...   \n",
       "9   Assess the role of Louis XVI’s indecisiveness ...   \n",
       "10  What event directly led to the transformation ...   \n",
       "11  Which radical measure taken by the National As...   \n",
       "12  What was the immediate consequence of Louis XV...   \n",
       "13  Which governing body replaced the National Con...   \n",
       "14  What significant political change occurred in ...   \n",
       "15  Considering the financial difficulties faced b...   \n",
       "16  What role did the socio-economic pressures suc...   \n",
       "17  Examine the influence of the Enlightenment on ...   \n",
       "18  How did the financial crisis, exacerbated by p...   \n",
       "19  Discuss the immediate political repercussions ...   \n",
       "\n",
       "                                        graph_results  \\\n",
       "0   The economic policies of the Ancien Régime con...   \n",
       "1   The social and political structure of the Esta...   \n",
       "2   The text does not provide specific information...   \n",
       "3   Economic depression and military defeats playe...   \n",
       "4   The text does not provide specific information...   \n",
       "5   The text does not provide specific information...   \n",
       "6   The French Revolutionary Wars that began in 17...   \n",
       "7   The calling of the Estates-General in 1789 was...   \n",
       "8   The Enlightenment ideas played a crucial role ...   \n",
       "9   The text does not provide specific information...   \n",
       "10  On June 17, 1789, the deputies of the Third Es...   \n",
       "11  The Storming of the Bastille on July 14, 1789,...   \n",
       "12  The text does not provide information on the i...   \n",
       "13  The governing body that replaced the National ...   \n",
       "14  The significant political change that occurred...   \n",
       "15  The inconsistent and complex tax system in Fra...   \n",
       "16  The socio-economic pressures played a signific...   \n",
       "17  The text does not provide specific information...   \n",
       "18  The financial crisis in France was primarily c...   \n",
       "19  The Storming of the Bastille in July 1789 mark...   \n",
       "\n",
       "                               graph_source_documents  \n",
       "0   [page_content=\"\\ntext: % of the population by ...  \n",
       "1   [page_content='\\ntext: The French Revolution w...  \n",
       "2   [page_content='\\ntext:  introduction of the pr...  \n",
       "3   [page_content=\"\\ntext: % of the population by ...  \n",
       "4   [page_content='\\ntext:  introduction of the pr...  \n",
       "5   [page_content='\\ntext: The French Revolution w...  \n",
       "6   [page_content='\\ntext: The French Revolution w...  \n",
       "7   [page_content=\"\\ntext: % of the population by ...  \n",
       "8   [page_content='\\ntext:  introduction of the pr...  \n",
       "9   [page_content='\\ntext:  rituals with a detaile...  \n",
       "10  [page_content='\\ntext:  for delegates to the E...  \n",
       "11  [page_content='\\ntext: The French Revolution w...  \n",
       "12  [page_content='\\ntext:  rituals with a detaile...  \n",
       "13  [page_content='\\ntext: The French Revolution o...  \n",
       "14  [page_content='\\ntext: The French Revolution o...  \n",
       "15  [page_content=\"\\ntext: % of the population by ...  \n",
       "16  [page_content='\\ntext: There is significant di...  \n",
       "17  [page_content='\\ntext:  institutionalised the ...  \n",
       "18  [page_content=\"\\ntext: % of the population by ...  \n",
       "19  [page_content='\\ntext:  introduction of the pr...  "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "\n",
    "# Assuming questions, rag_results, graph_results are your lists\n",
    "df = pd.DataFrame({\n",
    "    'questions': questions,\n",
    "    'graph_results': graph_results,\n",
    "    'graph_source_documents': graph_source_documents\n",
    "})\n",
    "\n",
    "df.head(20)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>questions</th>\n",
       "      <th>graph_results</th>\n",
       "      <th>graph_source_documents</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>How did the economic policies of the Ancien Ré...</td>\n",
       "      <td>The economic policies of the Ancien Régime con...</td>\n",
       "      <td>\\ntext: % of the population by 1789. Although ...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>In what ways did the social and political stru...</td>\n",
       "      <td>The social and political structure of the Esta...</td>\n",
       "      <td>\\ntext: The French Revolution was a period of ...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>What role did economic depression and military...</td>\n",
       "      <td>Economic depression and military defeats playe...</td>\n",
       "      <td>\\ntext: % of the population by 1789. Although ...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>How did the French Revolutionary Wars affect t...</td>\n",
       "      <td>The French Revolutionary Wars that began in 17...</td>\n",
       "      <td>\\ntext: The French Revolution was a period of ...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>Examine the socio-economic reasons behind the ...</td>\n",
       "      <td>The calling of the Estates-General in 1789 was...</td>\n",
       "      <td>\\ntext: % of the population by 1789. Although ...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>How did Enlightenment ideas influence the legi...</td>\n",
       "      <td>The Enlightenment ideas played a crucial role ...</td>\n",
       "      <td>\\ntext:  introduction of the principle of lega...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>What event directly led to the transformation ...</td>\n",
       "      <td>On June 17, 1789, the deputies of the Third Es...</td>\n",
       "      <td>\\ntext:  for delegates to the Estates-General\\...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>Which radical measure taken by the National As...</td>\n",
       "      <td>The Storming of the Bastille on July 14, 1789,...</td>\n",
       "      <td>\\ntext: The French Revolution was a period of ...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>Which governing body replaced the National Con...</td>\n",
       "      <td>The governing body that replaced the National ...</td>\n",
       "      <td>\\ntext: The French Revolution of 1848 (French:...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>What significant political change occurred in ...</td>\n",
       "      <td>The significant political change that occurred...</td>\n",
       "      <td>\\ntext: The French Revolution of 1848 (French:...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>Considering the financial difficulties faced b...</td>\n",
       "      <td>The inconsistent and complex tax system in Fra...</td>\n",
       "      <td>\\ntext: % of the population by 1789. Although ...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>11</th>\n",
       "      <td>What role did the socio-economic pressures suc...</td>\n",
       "      <td>The socio-economic pressures played a signific...</td>\n",
       "      <td>\\ntext: There is significant disagreement amon...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>12</th>\n",
       "      <td>How did the financial crisis, exacerbated by p...</td>\n",
       "      <td>The financial crisis in France was primarily c...</td>\n",
       "      <td>\\ntext: % of the population by 1789. Although ...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>13</th>\n",
       "      <td>Discuss the immediate political repercussions ...</td>\n",
       "      <td>The Storming of the Bastille in July 1789 mark...</td>\n",
       "      <td>\\ntext:  introduction of the principle of lega...</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                                            questions  \\\n",
       "0   How did the economic policies of the Ancien Ré...   \n",
       "1   In what ways did the social and political stru...   \n",
       "2   What role did economic depression and military...   \n",
       "3   How did the French Revolutionary Wars affect t...   \n",
       "4   Examine the socio-economic reasons behind the ...   \n",
       "5   How did Enlightenment ideas influence the legi...   \n",
       "6   What event directly led to the transformation ...   \n",
       "7   Which radical measure taken by the National As...   \n",
       "8   Which governing body replaced the National Con...   \n",
       "9   What significant political change occurred in ...   \n",
       "10  Considering the financial difficulties faced b...   \n",
       "11  What role did the socio-economic pressures suc...   \n",
       "12  How did the financial crisis, exacerbated by p...   \n",
       "13  Discuss the immediate political repercussions ...   \n",
       "\n",
       "                                        graph_results  \\\n",
       "0   The economic policies of the Ancien Régime con...   \n",
       "1   The social and political structure of the Esta...   \n",
       "2   Economic depression and military defeats playe...   \n",
       "3   The French Revolutionary Wars that began in 17...   \n",
       "4   The calling of the Estates-General in 1789 was...   \n",
       "5   The Enlightenment ideas played a crucial role ...   \n",
       "6   On June 17, 1789, the deputies of the Third Es...   \n",
       "7   The Storming of the Bastille on July 14, 1789,...   \n",
       "8   The governing body that replaced the National ...   \n",
       "9   The significant political change that occurred...   \n",
       "10  The inconsistent and complex tax system in Fra...   \n",
       "11  The socio-economic pressures played a signific...   \n",
       "12  The financial crisis in France was primarily c...   \n",
       "13  The Storming of the Bastille in July 1789 mark...   \n",
       "\n",
       "                               graph_source_documents  \n",
       "0   \\ntext: % of the population by 1789. Although ...  \n",
       "1   \\ntext: The French Revolution was a period of ...  \n",
       "2   \\ntext: % of the population by 1789. Although ...  \n",
       "3   \\ntext: The French Revolution was a period of ...  \n",
       "4   \\ntext: % of the population by 1789. Although ...  \n",
       "5   \\ntext:  introduction of the principle of lega...  \n",
       "6   \\ntext:  for delegates to the Estates-General\\...  \n",
       "7   \\ntext: The French Revolution was a period of ...  \n",
       "8   \\ntext: The French Revolution of 1848 (French:...  \n",
       "9   \\ntext: The French Revolution of 1848 (French:...  \n",
       "10  \\ntext: % of the population by 1789. Although ...  \n",
       "11  \\ntext: There is significant disagreement amon...  \n",
       "12  \\ntext: % of the population by 1789. Although ...  \n",
       "13  \\ntext:  introduction of the principle of lega...  "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "graphrag_text = []\n",
    "for index, row in df.iterrows():\n",
    "    graphrag_documents = row['graph_source_documents']\n",
    "    combined_graphrag_documents = \" \".join(doc.page_content for doc in graphrag_documents)\n",
    "    graphrag_text.append(combined_graphrag_documents)\n",
    "\n",
    "\n",
    "df.graph_source_documents = graphrag_text\n",
    "df.head(20)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "QUESTION\n",
      "How did the economic policies of the Ancien Régime contribute to the financial crisis that precipitated the French Revolution?\n",
      "\n",
      "ANSWER\n",
      "The economic policies of the Ancien Régime contributed to the financial crisis that precipitated the French Revolution in several ways. Firstly, the state had a high level of debt, although it was not high compared to Britain's. The tax system was a major issue, with tax rates varying widely from one region to another, often different from the official amounts, and collected inconsistently. This complexity created uncertainty over the amount any authorised tax actually contributed, and caused resentment among taxpayers.\n",
      "\n",
      "Attempts to simplify the system were blocked by the regional Parlements, which had the power to approve financial policy. This led to a financial impasse that contributed to the calling of the Estates-General, a representative assembly of the three estates (clergy, nobility, and commoners), which then became radicalised by the struggle for control of public finances.\n",
      "\n",
      "Moreover, the economic recession from 1785 and bad harvests in 1787 and 1788 led to high unemployment and food prices, which exacerbated the financial and political crisis for the monarchy. The state's inability to manage these crises effectively, combined with resistance to reform by the ruling elite and indecisive policy by Louis XVI and his ministers, escalated the situation into the French Revolution.\n",
      "\n",
      "CONTEXT\n",
      "\n",
      "text: % of the population by 1789. Although the 18th century was a period of increasing prosperity, the benefits were distributed unevenly across regions and social groups. Those whose income derived from agriculture, rents, interest and trade in goods from France's slave colonies benefited most, while the living standards of wage labourers and farmers on rented land fell. Increasing inequality led to more social conflict. Economic recession from 1785 and bad harvests in 1787 and 1788 led to high unemployment and food prices which coincided with a financial and political crisis for the monarchy.\n",
      "While the state also experienced a debt crisis, the level of debt itself was not high compared with Britain's. A major problem was that tax rates varied widely from one region to another, were often different from the official amounts, and collected inconsistently. Its complexity meant uncertainty over the amount any authorised tax actually contributed, and caused resentment among all taxpayers. Attempts to simplify the system were blocked by the regional Parlements which approved financial policy. The resulting impasse led to the calling of the Estates-General, which became radicalised by the struggle for control of public finances.\n",
      "Louis XVI was willing to consider reforms, but often backed down when faced with opposition from conservative elements within the nobility. Enlightenment critiques of social institutions were widely discussed among the educated French elite, while the American Revolution and the European revolts of the 1780s \n",
      "text: The French Revolution was a period of political and societal change in France that began with the Estates General of 1789, and ended with the coup of 18 Brumaire in November 1799 and the formation of the French Consulate. Many of its ideas are considered fundamental principles of liberal democracy, while its values and institutions remain central to modern French political discourse.\n",
      "Its causes are generally agreed to be a combination of social, political and economic factors, which the Ancien Régime proved unable to manage. A financial crisis and widespread social distress led in May 1789 to the convocation of the Estates General, which was converted into a National Assembly in June. The Storming of the Bastille on 14 July led to a series of radical measures by the Assembly, among them the abolition of feudalism, state control over the Catholic Church in France, and a declaration of rights.\n",
      "The next three years were dominated by the struggle for political control, exacerbated by economic depression. Military defeats following the outbreak of the French Revolutionary Wars in April 1792 resulted in the insurrection of 10 August 1792. The monarchy was abolished and replaced by the French First Republic in September, while Louis XVI was executed in January 1793.\n",
      "After another revolt in June 1793, the constitution was suspended and effective political power passed from the National Convention to the Committee of Public Safety. About 16,000 people were executed in a Reign of Terror, which ended in July 1794. Weakened by external threats and internal opposition, the Republic was replaced in 1795 by the Directory. Four years later in 1799, the Consulate seized power in a military coup led by Napoleon Bonaparte. This is generally seen as marking the end of the Revolutionary period.\n",
      "\n",
      "\n",
      "== Causes ==\n",
      "\n",
      "The Revolution was the result of multiple long-term and short-term factors that culminated in a social, economic, financial and political crisis in the late 1780s. Combined with resistance to reform by the ruling elite, and indecisive policy by Louis XVI and his ministers, the state was unable to manage the crisis.\n",
      "Between 1715 and 1789, the French population grew from an estimated 21 to 28 million. The proportion of the population living in towns increased to 20%, and Paris alone had over 600,000 inhabitants. Peasants comprised about 80% of the population, but the middle classes tripled over the century, reaching almost 10% of the population by 1789. Although the 18th century was a period of increasing prosperity, the benefits were distributed \n",
      "text: There is significant disagreement among historians of the French Revolution as to its causes. Usually, they acknowledge the presence of several interlinked factors, but vary in the weight they attribute to each one. These factors include cultural changes, normally associated with the Enlightenment; social change and financial and economic difficulties; and the political actions of the involved parties. For centuries, the French society was divided into three estates or orders. \n",
      "\n",
      "The first estate, the highest class, consisted of clergy.\n",
      "The second estate consisted of the nobility.\n",
      "The third estate consisted of the commoners.  It included businessman, merchants, court officials, lawyers, peasants, landless labourers and servants.\n",
      "The first two estates together were 10% of the population.  The third estate was 90%.  All of the many types of taxes were paid by the third estate.  The society was based on the old French maxim \"The nobles fight; the clergy pray and the people pay\". \n",
      "Beyond these relatively established facts about the social conditions surrounding the French Revolution, there is significant dissent among historians. Marxist historians, such as Lefebvre and Soboul, see the social tensions described here as the main cause of the revolution, as the Estates-General allowed them to manifest into tangible political action; the bourgeoisie and the lower classes were grouped into the third estate, allowing them to jointly oppose the establishment. Others see these social issues as important, but less so than the Enlightenment or the financial crisis; François Furet is a prominent proponent of the former, Simon Schama of the latter.\n",
      "\n",
      "\n",
      "== Political background ==\n",
      "\n",
      "Prior to the revolution, France was a de jure absolute monarchy, a system that became known as the Ancien Régime. In practice, the power of the monarchy was typically checked by the nobility, the Roman Catholic Church, institutions such as the judicial parlements, national and local customs and, above all, the threat of insurrection. Prior to 1789, the last severe threat to the monarchy was the Fronde civil wars from 1648 to 1653, during the minority of Louis XIV. Although the earlier reign of Louis XIII had already seen a move towards centralization of the country, the adulthood of Louis XIV marked the peak of the French monarchy's power. His tactics for bringing the nobility under control included inviting them to stay at his extravagant Palace of Versailles and participate in elaborate court rituals with a detailed code of etiquette.\n",
      "Some scholars have argued that Louis XIV contributed to the monarchy's downfall by failing \n",
      "text:  introduction of the principle of legal equality, and the downgrading of the once powerful and rich Catholic Church to just a bureau controlled by the government. Power became centralized in Paris, with its strong bureaucracy and an army supplied by conscripting all young men. French politics were permanently polarized—'left' and 'right'  were the new terms for the supporters and opponents of the principles of the Revolution.\n",
      "\n",
      "\n",
      "== Impact on France ==\n",
      "\n",
      "The changes in France were enormous; some were widely accepted and others were bitterly contested into the late 20th century.  Before the Revolution, the people had little power or voice. The kings had so thoroughly centralized the system that most nobles spent their time at Versailles, and played only a small direct role in their home districts. Thompson says that the kings had:\n",
      "\"ruled by virtue of their personal wealth, their patronage of the nobility, their disposal of ecclesiastical offices, their provincial governors (intendants), their control over the judges and magistrates, and their command of the Army.\"\n",
      "After the first year of revolution, this power had been stripped away. The king was a figurehead, the nobility had lost all their titles and most of their land, the Church lost its monasteries and farmlands, bishops, judges and magistrates were elected by the people, the army was almost helpless, with military power in the hands of the new revolutionary National Guard. T\n"
     ]
    }
   ],
   "source": [
    "print('QUESTION')\n",
    "print(df.iloc[0]['questions'])\n",
    "#printing whitespace\n",
    "print('')\n",
    "print('ANSWER')\n",
    "print(df.iloc[0]['graph_results'])\n",
    "print('')\n",
    "print('CONTEXT')\n",
    "print(df.iloc[0]['graph_source_documents'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Evaluation metrics"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_core.prompts import PromptTemplate\n",
    "from langchain.chains import LLMChain\n",
    "\n",
    "groundedness_critique_prompt = PromptTemplate.from_template(\"\"\"\n",
    "You will be given a context and answer about that context.\n",
    "Your task is to provide a 'total rating' scoring how well the ANSWER is entailed by the CONTEXT. \n",
    "Give your answer on a scale of 1 to 5, where 1 means that the ANSWER is logically false from the information contained in the CONTEXT, and 5 means that the ANSWER follows logically from the information contained in the CONTEXT.\n",
    "\n",
    "Provide your response in a list as follows:\n",
    "\n",
    "Response:::\n",
    "[Evaluation: (your rationale for the rating, as a text),\n",
    "Total rating: (your rating, as a number between 1 and 5)]\n",
    "\n",
    "You MUST provide values for 'Evaluation:' and 'Total rating:' in your response.\n",
    "\n",
    "Now here are the context, question and answer.\n",
    "\n",
    "Context: {context}\\n\n",
    "Answer: {answer}\\n\n",
    "Response::: \"\"\")\n",
    "\n",
    "relevance_critique_prompt = PromptTemplate.from_template(\"\"\"\n",
    "You will be given a context, and question and answer about that context.\n",
    "Your task is to provide a 'total rating' to measure how well the answer addresses the main aspects of the question, based on the context. \n",
    "Consider whether all and only the important aspects are contained in the answer when evaluating relevance. \n",
    "Given the context and question, score the relevance of the answer between one to five stars using the following rating scale: \n",
    "\n",
    "Give your response on a scale of 1 to 5, where 1 means that the answer doesn't address the question at all, and 5 means that the answer is perfectly matching the question.\n",
    "\n",
    "Provide your response in a list as follows:\n",
    "\n",
    "Response:::\n",
    "[Evaluation: (your rationale for the rating, as a text),\n",
    "Total rating: (your rating, as a number between 1 and 5)]\n",
    "\n",
    "You MUST provide values for 'Evaluation:' and 'Total rating:' in your response.\n",
    "\n",
    "Now here is the question.\n",
    "\n",
    "Answer: {answer}\\n\n",
    "Question: {question}\\n\n",
    "Context: {context}\\n\n",
    "Response::: \"\"\")\n",
    "\n",
    "coherence_critique_prompt = PromptTemplate.from_template(\"\"\"\n",
    "You will be given a question and answer.\n",
    "Your task is to measure the coherence of the answer. Coherence is measured by how well all the sentences fit together and sound naturally as a whole. Consider the overall quality of the answer when evaluating coherence. \n",
    "Given the question and answer, score the coherence of answer on a scale of 1 to 5, where 1 means that the answer completely lacks coherence, 5 means that the answer has perfect coherency.\n",
    "\n",
    "Provide your response in a list as follows:\n",
    "\n",
    "Response:::\n",
    "[Evaluation: (your rationale for the rating, as a text),\n",
    "Total rating: (your rating, as a number between 1 and 5)]\n",
    "\n",
    "You MUST provide values for 'Evaluation:' and 'Total rating:' in your response.\n",
    "\n",
    "Now here is the question.\n",
    "\n",
    "Question: {question}\\n\n",
    "Answer: {answer}\\n\n",
    "Response::: \"\"\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Graph evaluation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "groundness = []\n",
    "relevance = []\n",
    "coherence = []\n",
    "for i in range(len(df)):\n",
    "    question = df.iloc[i]['questions']\n",
    "    answer = df.iloc[i]['graph_results']\n",
    "    context = df.iloc[i]['graph_source_documents']\n",
    "    groundness_chain = LLMChain(llm=llm, prompt=groundedness_critique_prompt)\n",
    "    groundness.append(groundness_chain.run(context=context, answer = answer))\n",
    "    relevance_chain = LLMChain(llm=llm, prompt=relevance_critique_prompt)\n",
    "    relevance.append(relevance_chain.run(question=question, answer = answer, context = context))\n",
    "    coherence_chain = LLMChain(llm=llm, prompt=coherence_critique_prompt)\n",
    "    coherence.append(coherence_chain.run(question=question, answer = answer))\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>questions</th>\n",
       "      <th>graph_results</th>\n",
       "      <th>graph_source_documents</th>\n",
       "      <th>groundness</th>\n",
       "      <th>relevance</th>\n",
       "      <th>coherence</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>How did the economic policies of the Ancien Ré...</td>\n",
       "      <td>The economic policies of the Ancien Régime con...</td>\n",
       "      <td>\\ntext: % of the population by 1789. Although ...</td>\n",
       "      <td>Evaluation: The ANSWER correctly identifies se...</td>\n",
       "      <td>[Evaluation: The answer provides a comprehensi...</td>\n",
       "      <td>[Evaluation: The answer demonstrates a high le...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>In what ways did the social and political stru...</td>\n",
       "      <td>The social and political structure of the Esta...</td>\n",
       "      <td>\\ntext: The French Revolution was a period of ...</td>\n",
       "      <td>[Evaluation: The ANSWER accurately reflects th...</td>\n",
       "      <td>[Evaluation: The answer thoroughly addresses t...</td>\n",
       "      <td>[Evaluation: The answer is well-structured and...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>What role did economic depression and military...</td>\n",
       "      <td>Economic depression and military defeats playe...</td>\n",
       "      <td>\\ntext: % of the population by 1789. Although ...</td>\n",
       "      <td>[Evaluation: The ANSWER is well supported by t...</td>\n",
       "      <td>[Evaluation: The answer provides a comprehensi...</td>\n",
       "      <td>[Evaluation: The answer is coherent and presen...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>How did the French Revolutionary Wars affect t...</td>\n",
       "      <td>The French Revolutionary Wars that began in 17...</td>\n",
       "      <td>\\ntext: The French Revolution was a period of ...</td>\n",
       "      <td>[Evaluation: The ANSWER provides a summary of ...</td>\n",
       "      <td>[Evaluation: The answer provided is comprehens...</td>\n",
       "      <td>[Evaluation: The answer is coherent, providing...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>Examine the socio-economic reasons behind the ...</td>\n",
       "      <td>The calling of the Estates-General in 1789 was...</td>\n",
       "      <td>\\ntext: % of the population by 1789. Although ...</td>\n",
       "      <td>[Evaluation: The answer aligns closely with th...</td>\n",
       "      <td>[Evaluation: The answer provides a comprehensi...</td>\n",
       "      <td>[Evaluation: The answer presents a coherent na...</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                                           questions  \\\n",
       "0  How did the economic policies of the Ancien Ré...   \n",
       "1  In what ways did the social and political stru...   \n",
       "2  What role did economic depression and military...   \n",
       "3  How did the French Revolutionary Wars affect t...   \n",
       "4  Examine the socio-economic reasons behind the ...   \n",
       "\n",
       "                                       graph_results  \\\n",
       "0  The economic policies of the Ancien Régime con...   \n",
       "1  The social and political structure of the Esta...   \n",
       "2  Economic depression and military defeats playe...   \n",
       "3  The French Revolutionary Wars that began in 17...   \n",
       "4  The calling of the Estates-General in 1789 was...   \n",
       "\n",
       "                              graph_source_documents  \\\n",
       "0  \\ntext: % of the population by 1789. Although ...   \n",
       "1  \\ntext: The French Revolution was a period of ...   \n",
       "2  \\ntext: % of the population by 1789. Although ...   \n",
       "3  \\ntext: The French Revolution was a period of ...   \n",
       "4  \\ntext: % of the population by 1789. Although ...   \n",
       "\n",
       "                                          groundness  \\\n",
       "0  Evaluation: The ANSWER correctly identifies se...   \n",
       "1  [Evaluation: The ANSWER accurately reflects th...   \n",
       "2  [Evaluation: The ANSWER is well supported by t...   \n",
       "3  [Evaluation: The ANSWER provides a summary of ...   \n",
       "4  [Evaluation: The answer aligns closely with th...   \n",
       "\n",
       "                                           relevance  \\\n",
       "0  [Evaluation: The answer provides a comprehensi...   \n",
       "1  [Evaluation: The answer thoroughly addresses t...   \n",
       "2  [Evaluation: The answer provides a comprehensi...   \n",
       "3  [Evaluation: The answer provided is comprehens...   \n",
       "4  [Evaluation: The answer provides a comprehensi...   \n",
       "\n",
       "                                           coherence  \n",
       "0  [Evaluation: The answer demonstrates a high le...  \n",
       "1  [Evaluation: The answer is well-structured and...  \n",
       "2  [Evaluation: The answer is coherent and presen...  \n",
       "3  [Evaluation: The answer is coherent, providing...  \n",
       "4  [Evaluation: The answer presents a coherent na...  "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "#adding the three lists groundness, relevance and standalone to the dataframe\n",
    "df['groundness'] = groundness\n",
    "df['relevance'] = relevance\n",
    "df['coherence'] = coherence\n",
    "df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Evaluation: The answer provides a comprehensive overview of how the economic policies of the Ancien Régime contributed to the financial crisis that led to the French Revolution. It addresses the state's high level of debt, the inconsistent and complex tax system, the resistance to reform by regional Parlements, the economic recession, and the bad harvests that led to high unemployment and food prices. The answer also situates these factors in the broader context of resistance to reform by the ruling elite and indecision by Louis XVI. All of these points reflect the significant aspects mentioned in the provided context regarding the economic policies and their contribution to the crisis. Therefore, the answer is well-aligned with the context and the question asked.\n",
      "Total rating: 5]\n"
     ]
    }
   ],
   "source": [
    "print(df.iloc[0]['relevance'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "QUESTION\n",
      "How did the economic policies of the Ancien Régime contribute to the financial crisis that precipitated the French Revolution?\n",
      "\n",
      "ANSWER\n",
      "The economic policies of the Ancien Régime contributed to the financial crisis that precipitated the French Revolution in several ways. Firstly, the state had a high level of debt, although it was not high compared to Britain's. The tax system was a major issue, with tax rates varying widely from one region to another, often different from the official amounts, and collected inconsistently. This complexity created uncertainty over the amount any authorised tax actually contributed, and caused resentment among taxpayers.\n",
      "\n",
      "Attempts to simplify the system were blocked by the regional Parlements, which had the power to approve financial policy. This led to a financial impasse that contributed to the calling of the Estates-General, a representative assembly of the three estates (clergy, nobility, and commoners), which then became radicalised by the struggle for control of public finances.\n",
      "\n",
      "Moreover, the economic recession from 1785 and bad harvests in 1787 and 1788 led to high unemployment and food prices, which exacerbated the financial and political crisis for the monarchy. The state's inability to manage these crises effectively, combined with resistance to reform by the ruling elite and indecisive policy by Louis XVI and his ministers, escalated the situation into the French Revolution.\n",
      "\n",
      "CONTEXT\n",
      "\n",
      "text: % of the population by 1789. Although the 18th century was a period of increasing prosperity, the benefits were distributed unevenly across regions and social groups. Those whose income derived from agriculture, rents, interest and trade in goods from France's slave colonies benefited most, while the living standards of wage labourers and farmers on rented land fell. Increasing inequality led to more social conflict. Economic recession from 1785 and bad harvests in 1787 and 1788 led to high unemployment and food prices which coincided with a financial and political crisis for the monarchy.\n",
      "While the state also experienced a debt crisis, the level of debt itself was not high compared with Britain's. A major problem was that tax rates varied widely from one region to another, were often different from the official amounts, and collected inconsistently. Its complexity meant uncertainty over the amount any authorised tax actually contributed, and caused resentment among all taxpayers. Attempts to simplify the system were blocked by the regional Parlements which approved financial policy. The resulting impasse led to the calling of the Estates-General, which became radicalised by the struggle for control of public finances.\n",
      "Louis XVI was willing to consider reforms, but often backed down when faced with opposition from conservative elements within the nobility. Enlightenment critiques of social institutions were widely discussed among the educated French elite, while the American Revolution and the European revolts of the 1780s \n",
      "text: The French Revolution was a period of political and societal change in France that began with the Estates General of 1789, and ended with the coup of 18 Brumaire in November 1799 and the formation of the French Consulate. Many of its ideas are considered fundamental principles of liberal democracy, while its values and institutions remain central to modern French political discourse.\n",
      "Its causes are generally agreed to be a combination of social, political and economic factors, which the Ancien Régime proved unable to manage. A financial crisis and widespread social distress led in May 1789 to the convocation of the Estates General, which was converted into a National Assembly in June. The Storming of the Bastille on 14 July led to a series of radical measures by the Assembly, among them the abolition of feudalism, state control over the Catholic Church in France, and a declaration of rights.\n",
      "The next three years were dominated by the struggle for political control, exacerbated by economic depression. Military defeats following the outbreak of the French Revolutionary Wars in April 1792 resulted in the insurrection of 10 August 1792. The monarchy was abolished and replaced by the French First Republic in September, while Louis XVI was executed in January 1793.\n",
      "After another revolt in June 1793, the constitution was suspended and effective political power passed from the National Convention to the Committee of Public Safety. About 16,000 people were executed in a Reign of Terror, which ended in July 1794. Weakened by external threats and internal opposition, the Republic was replaced in 1795 by the Directory. Four years later in 1799, the Consulate seized power in a military coup led by Napoleon Bonaparte. This is generally seen as marking the end of the Revolutionary period.\n",
      "\n",
      "\n",
      "== Causes ==\n",
      "\n",
      "The Revolution was the result of multiple long-term and short-term factors that culminated in a social, economic, financial and political crisis in the late 1780s. Combined with resistance to reform by the ruling elite, and indecisive policy by Louis XVI and his ministers, the state was unable to manage the crisis.\n",
      "Between 1715 and 1789, the French population grew from an estimated 21 to 28 million. The proportion of the population living in towns increased to 20%, and Paris alone had over 600,000 inhabitants. Peasants comprised about 80% of the population, but the middle classes tripled over the century, reaching almost 10% of the population by 1789. Although the 18th century was a period of increasing prosperity, the benefits were distributed \n",
      "text: There is significant disagreement among historians of the French Revolution as to its causes. Usually, they acknowledge the presence of several interlinked factors, but vary in the weight they attribute to each one. These factors include cultural changes, normally associated with the Enlightenment; social change and financial and economic difficulties; and the political actions of the involved parties. For centuries, the French society was divided into three estates or orders. \n",
      "\n",
      "The first estate, the highest class, consisted of clergy.\n",
      "The second estate consisted of the nobility.\n",
      "The third estate consisted of the commoners.  It included businessman, merchants, court officials, lawyers, peasants, landless labourers and servants.\n",
      "The first two estates together were 10% of the population.  The third estate was 90%.  All of the many types of taxes were paid by the third estate.  The society was based on the old French maxim \"The nobles fight; the clergy pray and the people pay\". \n",
      "Beyond these relatively established facts about the social conditions surrounding the French Revolution, there is significant dissent among historians. Marxist historians, such as Lefebvre and Soboul, see the social tensions described here as the main cause of the revolution, as the Estates-General allowed them to manifest into tangible political action; the bourgeoisie and the lower classes were grouped into the third estate, allowing them to jointly oppose the establishment. Others see these social issues as important, but less so than the Enlightenment or the financial crisis; François Furet is a prominent proponent of the former, Simon Schama of the latter.\n",
      "\n",
      "\n",
      "== Political background ==\n",
      "\n",
      "Prior to the revolution, France was a de jure absolute monarchy, a system that became known as the Ancien Régime. In practice, the power of the monarchy was typically checked by the nobility, the Roman Catholic Church, institutions such as the judicial parlements, national and local customs and, above all, the threat of insurrection. Prior to 1789, the last severe threat to the monarchy was the Fronde civil wars from 1648 to 1653, during the minority of Louis XIV. Although the earlier reign of Louis XIII had already seen a move towards centralization of the country, the adulthood of Louis XIV marked the peak of the French monarchy's power. His tactics for bringing the nobility under control included inviting them to stay at his extravagant Palace of Versailles and participate in elaborate court rituals with a detailed code of etiquette.\n",
      "Some scholars have argued that Louis XIV contributed to the monarchy's downfall by failing \n",
      "text:  introduction of the principle of legal equality, and the downgrading of the once powerful and rich Catholic Church to just a bureau controlled by the government. Power became centralized in Paris, with its strong bureaucracy and an army supplied by conscripting all young men. French politics were permanently polarized—'left' and 'right'  were the new terms for the supporters and opponents of the principles of the Revolution.\n",
      "\n",
      "\n",
      "== Impact on France ==\n",
      "\n",
      "The changes in France were enormous; some were widely accepted and others were bitterly contested into the late 20th century.  Before the Revolution, the people had little power or voice. The kings had so thoroughly centralized the system that most nobles spent their time at Versailles, and played only a small direct role in their home districts. Thompson says that the kings had:\n",
      "\"ruled by virtue of their personal wealth, their patronage of the nobility, their disposal of ecclesiastical offices, their provincial governors (intendants), their control over the judges and magistrates, and their command of the Army.\"\n",
      "After the first year of revolution, this power had been stripped away. The king was a figurehead, the nobility had lost all their titles and most of their land, the Church lost its monasteries and farmlands, bishops, judges and magistrates were elected by the people, the army was almost helpless, with military power in the hands of the new revolutionary National Guard. T\n",
      "\n",
      "GROUNDNESS\n",
      "Evaluation: The provided context includes detailed information about the social, economic, and political conditions leading up to the French Revolution. It outlines the uneven distribution of prosperity, the financial struggles of the monarchy, the complex and inconsistent tax system, the resistance to reform, the influence of the Enlightenment, and the power dynamics of the Ancien Régime. Specific details such as the debt crisis, regional variation in tax rates, and the rejection of tax system reforms by the regional Parlements, as well as the role of social classes, are directly relevant to understanding how economic policies contributed to the financial crisis that precipitated the Revolution. Although there is some acknowledgment of disagreement among historians, the context provided is sufficiently comprehensive to answer the question about the contribution of economic policies to the financial crisis unambiguously.\n",
      "\n",
      "Total rating: 4\n",
      "\n",
      "RELEVANCE\n",
      "Evaluation: The question is highly relevant to the understanding of the causes behind the French Revolution. It asks for an analysis of the economic policies prior to the Revolution and how they led to a financial crisis, which is a key aspect of the historical context. Understanding these economic factors is crucial for anyone studying the French Revolution, as it helps explain the discontent among the populace and the subsequent political upheaval. The question promotes a deep dive into the fiscal management, tax system, and economic conditions of the period, which are important topics for students of history, economics, and political science.\n",
      "\n",
      "Total rating: 5\n",
      "\n",
      "STANDALONE\n",
      "Evaluation: The question is asking about the relationship between the economic policies of a specific historical period (the Ancien Régime) and the financial crisis leading up to a major historical event (the French Revolution). The question is clear and does not depend on additional context to be understood. It is a historical inquiry that can be addressed with knowledge of European history and economic theory. An operator with access to historical documentation and analysis can understand and respond to the question.\n",
      "\n",
      "Total rating: 5\n"
     ]
    }
   ],
   "source": [
    "#printing the content of each column in the first row of the dataframe, separating the name of the column from the content of the cell\n",
    "print('QUESTION')\n",
    "print(df.iloc[0]['questions'])\n",
    "#printing whitespace\n",
    "print('')\n",
    "print('ANSWER')\n",
    "print(df.iloc[0]['graph_results'])\n",
    "print('')\n",
    "print('CONTEXT')\n",
    "print(df.iloc[0]['graph_source_documents'])\n",
    "print('')\n",
    "print('GROUNDNESS')\n",
    "print(df.iloc[0]['groundness'])\n",
    "print('')\n",
    "print('RELEVANCE')\n",
    "print(df.iloc[0]['relevance'])\n",
    "print('')\n",
    "print('STANDALONE')\n",
    "print(df.iloc[0]['standalone'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Save the DataFrame to an Excel file\n",
    "df.to_excel('graphrag_results.xlsx', index=False)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
